code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : List[Any] = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys _a : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
1
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __A ( SCREAMING_SNAKE_CASE_ ): def __A ( self ): _lowerCAmelCase : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a__ , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(a__ , """num_attention_heads""" ) ) class __A : def __init__( self , a__ , a__=13 , a__=64 , a__=3 , a__=3 , a__=2 , a__=1 , a__=16 , a__=[128, 256, 384] , a__=[4, 6, 8] , a__=[2, 3, 4] , a__=[16, 16, 16] , a__=0 , a__=[2, 2, 2] , a__=[2, 2, 2] , a__=0.0_2 , a__=True , a__=True , a__=2 , ): _lowerCAmelCase : int = parent _lowerCAmelCase : List[str] = batch_size _lowerCAmelCase : Optional[Any] = image_size _lowerCAmelCase : Optional[int] = num_channels _lowerCAmelCase : Optional[Any] = kernel_size _lowerCAmelCase : str = stride _lowerCAmelCase : List[Any] = padding _lowerCAmelCase : Tuple = hidden_sizes _lowerCAmelCase : Tuple = num_attention_heads _lowerCAmelCase : Any = depths _lowerCAmelCase : List[Any] = key_dim _lowerCAmelCase : Any = drop_path_rate _lowerCAmelCase : Dict = patch_size _lowerCAmelCase : List[Any] = attention_ratio _lowerCAmelCase : Any = mlp_ratio _lowerCAmelCase : Tuple = initializer_range _lowerCAmelCase : Any = [ ["""Subsample""", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["""Subsample""", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] _lowerCAmelCase : Optional[Any] = is_training _lowerCAmelCase : Dict = use_labels _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : List[Any] = initializer_range def __A ( self ): _lowerCAmelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Optional[int] = None if self.use_labels: _lowerCAmelCase : Any = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase : List[str] = self.get_config() return config, pixel_values, labels def __A ( self ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = LevitModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ ) _lowerCAmelCase : List[Any] = (self.image_size, self.image_size) _lowerCAmelCase , _lowerCAmelCase : Optional[int] = image_size[0], image_size[1] for _ in range(4 ): _lowerCAmelCase : Tuple = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) _lowerCAmelCase : Tuple = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = LevitForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self ): _lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Any = config_and_inputs _lowerCAmelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) _UpperCamelCase : Optional[Any] = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) _UpperCamelCase : Dict = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : str = False _UpperCamelCase : Union[str, Any] = False def __A ( self ): _lowerCAmelCase : Union[str, Any] = LevitModelTester(self ) _lowerCAmelCase : str = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __A ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ): return @unittest.skip(reason="""Levit does not use inputs_embeds""" ) def __A ( self ): pass @unittest.skip(reason="""Levit does not support input and output embeddings""" ) def __A ( self ): pass @unittest.skip(reason="""Levit does not output attentions""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : str = model_class(a__ ) _lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : int = [*signature.parameters.keys()] _lowerCAmelCase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def __A ( self ): def check_hidden_states_output(a__ , a__ , a__ ): _lowerCAmelCase : Any = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): _lowerCAmelCase : int = model(**self._prepare_for_class(a__ , a__ ) ) _lowerCAmelCase : Optional[Any] = outputs.hidden_states _lowerCAmelCase : List[str] = len(self.model_tester.depths ) + 1 self.assertEqual(len(a__ ) , a__ ) _lowerCAmelCase : Dict = (self.model_tester.image_size, self.model_tester.image_size) _lowerCAmelCase , _lowerCAmelCase : List[str] = image_size[0], image_size[1] for _ in range(4 ): _lowerCAmelCase : Union[str, Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) _lowerCAmelCase : Optional[Any] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) _lowerCAmelCase , _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : List[str] = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase : str = True check_hidden_states_output(a__ , a__ , a__ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __A ( self ): pass def __A ( self , a__ , a__ , a__=False ): _lowerCAmelCase : Dict = super()._prepare_for_class(a__ , a__ , return_labels=a__ ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) def __A ( self ): if not self.model_tester.is_training: return _lowerCAmelCase , _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : int = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a__ ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue _lowerCAmelCase : Dict = model_class(a__ ) model.to(a__ ) model.train() _lowerCAmelCase : Optional[Any] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) _lowerCAmelCase : Optional[Any] = model(**a__ ).loss loss.backward() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _lowerCAmelCase : List[Any] = False _lowerCAmelCase : 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 # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue _lowerCAmelCase : List[str] = model_class(a__ ) model.gradient_checkpointing_enable() model.to(a__ ) model.train() _lowerCAmelCase : Optional[Any] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) _lowerCAmelCase : Tuple = model(**a__ ).loss loss.backward() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : Optional[Any] = [ {"""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__ ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"Testing {model_class} with {problem_type['title']}" ): _lowerCAmelCase : Optional[int] = problem_type["""title"""] _lowerCAmelCase : List[Any] = problem_type["""num_labels"""] _lowerCAmelCase : Optional[int] = model_class(a__ ) model.to(a__ ) model.train() _lowerCAmelCase : Optional[int] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) if problem_type["num_labels"] > 1: _lowerCAmelCase : str = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) _lowerCAmelCase : 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: _lowerCAmelCase : Optional[int] = 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 __A ( self ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Optional[Any] = LevitModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def SCREAMING_SNAKE_CASE ( ) -> Tuple: _lowerCAmelCase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def __A ( self ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __A ( self ): _lowerCAmelCase : int = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( a__ ) _lowerCAmelCase : Tuple = self.default_image_processor _lowerCAmelCase : List[str] = prepare_img() _lowerCAmelCase : int = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Any = model(**a__ ) # verify the logits _lowerCAmelCase : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) _lowerCAmelCase : Dict = torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) )
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
1
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A : def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=None , a__=2 , ): _lowerCAmelCase : List[Any] = parent _lowerCAmelCase : int = batch_size _lowerCAmelCase : Tuple = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : int = num_channels _lowerCAmelCase : List[str] = is_training _lowerCAmelCase : Tuple = use_labels _lowerCAmelCase : Any = hidden_size _lowerCAmelCase : List[Any] = num_hidden_layers _lowerCAmelCase : List[str] = num_attention_heads _lowerCAmelCase : Optional[Any] = intermediate_size _lowerCAmelCase : Any = hidden_act _lowerCAmelCase : Tuple = hidden_dropout_prob _lowerCAmelCase : Optional[Any] = attention_probs_dropout_prob _lowerCAmelCase : Any = type_sequence_label_size _lowerCAmelCase : int = initializer_range _lowerCAmelCase : Any = scope _lowerCAmelCase : Union[str, Any] = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _lowerCAmelCase : int = (image_size // patch_size) ** 2 _lowerCAmelCase : Optional[Any] = num_patches + 1 def __A ( self ): _lowerCAmelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Optional[int] = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def __A ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : str = ViTModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Any = ViTForMaskedImageModeling(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = model(a__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _lowerCAmelCase : Union[str, Any] = 1 _lowerCAmelCase : Union[str, Any] = ViTForMaskedImageModeling(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : Dict = model(a__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Optional[int] = self.type_sequence_label_size _lowerCAmelCase : Dict = ViTForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : int = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _lowerCAmelCase : int = 1 _lowerCAmelCase : Dict = ViTForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : Tuple = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ): _lowerCAmelCase : Dict = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : List[str] = config_and_inputs _lowerCAmelCase : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : int = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _UpperCamelCase : Tuple = ( {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification} if is_torch_available() else {} ) _UpperCamelCase : Dict = True _UpperCamelCase : str = False _UpperCamelCase : Optional[Any] = False _UpperCamelCase : List[str] = False def __A ( self ): _lowerCAmelCase : Dict = ViTModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : List[str] = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCAmelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Optional[Any] = model_class(a__ ) _lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : List[str] = [*signature.parameters.keys()] _lowerCAmelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a__ ) def __A ( self ): _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def __A ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : List[str] = ViTModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def SCREAMING_SNAKE_CASE ( ) -> List[str]: _lowerCAmelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def __A ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __A ( self ): _lowerCAmelCase : Dict = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(a__ ) _lowerCAmelCase : str = self.default_image_processor _lowerCAmelCase : str = prepare_img() _lowerCAmelCase : Tuple = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Optional[int] = model(**a__ ) # verify the logits _lowerCAmelCase : str = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) _lowerCAmelCase : List[Any] = torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) ) @slow def __A ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. _lowerCAmelCase : Optional[Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(a__ ) _lowerCAmelCase : str = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) _lowerCAmelCase : Any = prepare_img() _lowerCAmelCase : Dict = image_processor(images=a__ , return_tensors="""pt""" ) _lowerCAmelCase : Optional[Any] = inputs.pixel_values.to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : str = model(a__ , interpolate_pos_encoding=a__ ) # verify the logits _lowerCAmelCase : str = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , a__ ) _lowerCAmelCase : Union[str, Any] = torch.tensor( [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]] ).to(a__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a__ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __A ( self ): _lowerCAmelCase : Optional[int] = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) _lowerCAmelCase : Union[str, Any] = self.default_image_processor _lowerCAmelCase : Dict = prepare_img() _lowerCAmelCase : List[str] = image_processor(images=a__ , return_tensors="""pt""" ) _lowerCAmelCase : Any = inputs.pixel_values.to(a__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): _lowerCAmelCase : Optional[int] = model(a__ )
44
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
1
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int] ,_lowerCamelCase : Union[str, Any]=0.9_99 ,_lowerCamelCase : Optional[int]="cosine" ,) -> Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(_lowerCamelCase : List[Any] ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_lowerCamelCase : List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) _lowerCAmelCase : str = [] for i in range(_lowerCamelCase ): _lowerCAmelCase : Optional[Any] = i / num_diffusion_timesteps _lowerCAmelCase : str = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_lowerCamelCase ) / alpha_bar_fn(_lowerCamelCase ) ,_lowerCamelCase ) ) return torch.tensor(_lowerCamelCase ,dtype=torch.floataa ) class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = [e.name for e in KarrasDiffusionSchedulers] _UpperCamelCase : Dict = 2 @register_to_config def __init__( self , a__ = 1000 , a__ = 0.0_0_0_8_5 , a__ = 0.0_1_2 , a__ = "linear" , a__ = None , a__ = "epsilon" , a__ = "linspace" , a__ = 0 , ): if trained_betas is not None: _lowerCAmelCase : str = torch.tensor(a__ , dtype=torch.floataa ) elif beta_schedule == "linear": _lowerCAmelCase : Optional[Any] = torch.linspace(a__ , a__ , a__ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _lowerCAmelCase : int = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , a__ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _lowerCAmelCase : Optional[Any] = betas_for_alpha_bar(a__ ) else: raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}" ) _lowerCAmelCase : List[str] = 1.0 - self.betas _lowerCAmelCase : Optional[int] = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(a__ , a__ , a__ ) def __A ( self , a__ , a__=None ): if schedule_timesteps is None: _lowerCAmelCase : Dict = self.timesteps _lowerCAmelCase : int = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _lowerCAmelCase : List[str] = 1 if len(a__ ) > 1 else 0 else: _lowerCAmelCase : Optional[int] = timestep.cpu().item() if torch.is_tensor(a__ ) else timestep _lowerCAmelCase : Optional[int] = self._index_counter[timestep_int] return indices[pos].item() @property def __A ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __A ( self , a__ , a__ , ): _lowerCAmelCase : Union[str, Any] = self.index_for_timestep(a__ ) if self.state_in_first_order: _lowerCAmelCase : Optional[int] = self.sigmas[step_index] else: _lowerCAmelCase : Optional[Any] = self.sigmas_interpol[step_index] _lowerCAmelCase : List[str] = sample / ((sigma**2 + 1) ** 0.5) return sample def __A ( self , a__ , a__ = None , a__ = None , ): _lowerCAmelCase : List[Any] = num_inference_steps _lowerCAmelCase : Tuple = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _lowerCAmelCase : List[str] = np.linspace(0 , num_train_timesteps - 1 , a__ , dtype=a__ )[::-1].copy() elif self.config.timestep_spacing == "leading": _lowerCAmelCase : Union[str, Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowerCAmelCase : List[str] = (np.arange(0 , a__ ) * step_ratio).round()[::-1].copy().astype(a__ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _lowerCAmelCase : Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowerCAmelCase : str = (np.arange(a__ , 0 , -step_ratio )).round().copy().astype(a__ ) timesteps -= 1 else: raise ValueError( F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." ) _lowerCAmelCase : Dict = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _lowerCAmelCase : List[str] = torch.from_numpy(np.log(a__ ) ).to(a__ ) _lowerCAmelCase : List[str] = np.interp(a__ , np.arange(0 , len(a__ ) ) , a__ ) _lowerCAmelCase : Dict = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _lowerCAmelCase : Any = torch.from_numpy(a__ ).to(device=a__ ) # interpolate sigmas _lowerCAmelCase : List[str] = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() _lowerCAmelCase : Dict = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) _lowerCAmelCase : Union[str, Any] = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(a__ ).startswith("""mps""" ): # mps does not support float64 _lowerCAmelCase : List[Any] = torch.from_numpy(a__ ).to(a__ , dtype=torch.floataa ) else: _lowerCAmelCase : List[str] = torch.from_numpy(a__ ).to(a__ ) # interpolate timesteps _lowerCAmelCase : List[Any] = self.sigma_to_t(a__ ).to(a__ , dtype=timesteps.dtype ) _lowerCAmelCase : Optional[Any] = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() _lowerCAmelCase : str = torch.cat([timesteps[:1], interleaved_timesteps] ) _lowerCAmelCase : Optional[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _lowerCAmelCase : Tuple = defaultdict(a__ ) def __A ( self , a__ ): # get log sigma _lowerCAmelCase : str = sigma.log() # get distribution _lowerCAmelCase : List[str] = log_sigma - self.log_sigmas[:, None] # get sigmas range _lowerCAmelCase : Optional[Any] = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) _lowerCAmelCase : List[str] = low_idx + 1 _lowerCAmelCase : str = self.log_sigmas[low_idx] _lowerCAmelCase : Union[str, Any] = self.log_sigmas[high_idx] # interpolate sigmas _lowerCAmelCase : List[Any] = (low - log_sigma) / (low - high) _lowerCAmelCase : List[str] = w.clamp(0 , 1 ) # transform interpolation to time range _lowerCAmelCase : Optional[Any] = (1 - w) * low_idx + w * high_idx _lowerCAmelCase : Optional[int] = t.view(sigma.shape ) return t @property def __A ( self ): return self.sample is None def __A ( self , a__ , a__ , a__ , a__ = True , ): _lowerCAmelCase : List[str] = self.index_for_timestep(a__ ) # advance index counter by 1 _lowerCAmelCase : str = timestep.cpu().item() if torch.is_tensor(a__ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _lowerCAmelCase : Tuple = self.sigmas[step_index] _lowerCAmelCase : Optional[int] = self.sigmas_interpol[step_index + 1] _lowerCAmelCase : Any = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method _lowerCAmelCase : int = self.sigmas[step_index - 1] _lowerCAmelCase : Any = self.sigmas_interpol[step_index] _lowerCAmelCase : List[str] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _lowerCAmelCase : int = 0 _lowerCAmelCase : Union[str, Any] = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _lowerCAmelCase : List[str] = sigma_hat if self.state_in_first_order else sigma_interpol _lowerCAmelCase : int = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _lowerCAmelCase : List[str] = sigma_hat if self.state_in_first_order else sigma_interpol _lowerCAmelCase : List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("""prediction_type not implemented yet: sample""" ) else: raise ValueError( F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _lowerCAmelCase : Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _lowerCAmelCase : Optional[Any] = sigma_interpol - sigma_hat # store for 2nd order step _lowerCAmelCase : Tuple = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order _lowerCAmelCase : List[Any] = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep _lowerCAmelCase : Union[str, Any] = sigma_next - sigma_hat _lowerCAmelCase : int = self.sample _lowerCAmelCase : List[Any] = None _lowerCAmelCase : Tuple = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=a__ ) def __A ( self , a__ , a__ , a__ , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples _lowerCAmelCase : Optional[Any] = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(a__ ): # mps does not support float64 _lowerCAmelCase : str = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _lowerCAmelCase : List[Any] = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _lowerCAmelCase : Any = self.timesteps.to(original_samples.device ) _lowerCAmelCase : int = timesteps.to(original_samples.device ) _lowerCAmelCase : str = [self.index_for_timestep(a__ , a__ ) for t in timesteps] _lowerCAmelCase : Union[str, Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _lowerCAmelCase : str = sigma.unsqueeze(-1 ) _lowerCAmelCase : Tuple = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
44
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
1
"""simple docstring""" 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 _a : Dict = 8 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ,_lowerCamelCase : Tuple=BITS ) -> Union[str, Any]: _lowerCAmelCase : Union[str, Any] = x.device _lowerCAmelCase : Any = (x * 255).int().clamp(0 ,255 ) _lowerCAmelCase : Union[str, Any] = 2 ** torch.arange(bits - 1 ,-1 ,-1 ,device=_lowerCamelCase ) _lowerCAmelCase : Any = rearrange(_lowerCamelCase ,"""d -> d 1 1""" ) _lowerCAmelCase : str = rearrange(_lowerCamelCase ,"""b c h w -> b c 1 h w""" ) _lowerCAmelCase : Dict = ((x & mask) != 0).float() _lowerCAmelCase : Any = rearrange(_lowerCamelCase ,"""b c d h w -> b (c d) h w""" ) _lowerCAmelCase : str = bits * 2 - 1 return bits def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int] ,_lowerCamelCase : Optional[Any]=BITS ) -> List[Any]: _lowerCAmelCase : List[str] = x.device _lowerCAmelCase : Optional[int] = (x > 0).int() _lowerCAmelCase : Optional[Any] = 2 ** torch.arange(bits - 1 ,-1 ,-1 ,device=_lowerCamelCase ,dtype=torch.intaa ) _lowerCAmelCase : Dict = rearrange(_lowerCamelCase ,"""d -> d 1 1""" ) _lowerCAmelCase : Dict = rearrange(_lowerCamelCase ,"""b (c d) h w -> b c d h w""" ,d=8 ) _lowerCAmelCase : Dict = reduce(x * mask ,"""b c d h w -> b c h w""" ,"""sum""" ) return (dec / 255).clamp(0.0 ,1.0 ) def SCREAMING_SNAKE_CASE ( self : List[Any] ,_lowerCamelCase : torch.FloatTensor ,_lowerCamelCase : int ,_lowerCamelCase : torch.FloatTensor ,_lowerCamelCase : float = 0.0 ,_lowerCamelCase : bool = True ,_lowerCamelCase : Union[str, Any]=None ,_lowerCamelCase : bool = True ,) -> Union[DDIMSchedulerOutput, Tuple]: 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) _lowerCAmelCase : Tuple = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _lowerCAmelCase : List[Any] = self.alphas_cumprod[timestep] _lowerCAmelCase : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _lowerCAmelCase : Union[str, Any] = 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 _lowerCAmelCase : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _lowerCAmelCase : List[Any] = self.bit_scale if self.config.clip_sample: _lowerCAmelCase : Union[str, Any] = torch.clamp(_lowerCamelCase ,-scale ,_lowerCamelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _lowerCAmelCase : Any = self._get_variance(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Any = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _lowerCAmelCase : Dict = (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 _lowerCAmelCase : Dict = (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 _lowerCAmelCase : Optional[Any] = 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 _lowerCAmelCase : List[Any] = model_output.device if torch.is_tensor(_lowerCamelCase ) else """cpu""" _lowerCAmelCase : Optional[Any] = torch.randn(model_output.shape ,dtype=model_output.dtype ,generator=_lowerCamelCase ).to(_lowerCamelCase ) _lowerCAmelCase : Tuple = self._get_variance(_lowerCamelCase ,_lowerCamelCase ) ** 0.5 * eta * noise _lowerCAmelCase : int = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=_lowerCamelCase ,pred_original_sample=_lowerCamelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,_lowerCamelCase : torch.FloatTensor ,_lowerCamelCase : int ,_lowerCamelCase : torch.FloatTensor ,_lowerCamelCase : Any="epsilon" ,_lowerCamelCase : str=None ,_lowerCamelCase : bool = True ,) -> Union[DDPMSchedulerOutput, Tuple]: _lowerCAmelCase : str = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _lowerCAmelCase , _lowerCAmelCase : int = torch.split(_lowerCamelCase ,sample.shape[1] ,dim=1 ) else: _lowerCAmelCase : Any = None # 1. compute alphas, betas _lowerCAmelCase : Dict = self.alphas_cumprod[t] _lowerCAmelCase : Union[str, Any] = self.alphas_cumprod[t - 1] if t > 0 else self.one _lowerCAmelCase : str = 1 - alpha_prod_t _lowerCAmelCase : Dict = 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": _lowerCAmelCase : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _lowerCAmelCase : str = model_output else: raise ValueError(f"Unsupported prediction_type {prediction_type}." ) # 3. Clip "predicted x_0" _lowerCAmelCase : Optional[int] = self.bit_scale if self.config.clip_sample: _lowerCAmelCase : List[Any] = torch.clamp(_lowerCamelCase ,-scale ,_lowerCamelCase ) # 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 _lowerCAmelCase : int = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _lowerCAmelCase : List[str] = 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 _lowerCAmelCase : List[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _lowerCAmelCase : Optional[Any] = 0 if t > 0: _lowerCAmelCase : Dict = torch.randn( model_output.size() ,dtype=model_output.dtype ,layout=model_output.layout ,generator=_lowerCamelCase ).to(model_output.device ) _lowerCAmelCase : List[str] = (self._get_variance(_lowerCamelCase ,predicted_variance=_lowerCamelCase ) ** 0.5) * noise _lowerCAmelCase : Optional[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=_lowerCamelCase ,pred_original_sample=_lowerCamelCase ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ , a__ = 1.0 , ): super().__init__() _lowerCAmelCase : Optional[int] = bit_scale _lowerCAmelCase : int = ( 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 , a__ = 256 , a__ = 256 , a__ = 50 , a__ = None , a__ = 1 , a__ = "pil" , a__ = True , **a__ , ): _lowerCAmelCase : Optional[int] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=a__ , ) _lowerCAmelCase : Dict = decimal_to_bits(a__ ) * self.bit_scale _lowerCAmelCase : Dict = latents.to(self.device ) self.scheduler.set_timesteps(a__ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual _lowerCAmelCase : Tuple = self.unet(a__ , a__ ).sample # compute the previous noisy sample x_t -> x_t-1 _lowerCAmelCase : Tuple = self.scheduler.step(a__ , a__ , a__ ).prev_sample _lowerCAmelCase : Dict = bits_to_decimal(a__ ) if output_type == "pil": _lowerCAmelCase : Optional[Any] = self.numpy_to_pil(a__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a__ )
44
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
44
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __A ( unittest.TestCase ): def __init__( self , a__ , a__=7 , a__=3 , a__=30 , a__=400 , a__=True , a__=None , a__=0.9 , a__=None , a__=True , a__=[0.5, 0.5, 0.5] , a__=[0.5, 0.5, 0.5] , ): _lowerCAmelCase : Dict = size if size is not None else {"""shortest_edge""": 30} _lowerCAmelCase : Union[str, Any] = crop_size if crop_size is not None else {"""height""": 30, """width""": 30} _lowerCAmelCase : List[str] = parent _lowerCAmelCase : int = batch_size _lowerCAmelCase : Optional[Any] = num_channels _lowerCAmelCase : List[Any] = min_resolution _lowerCAmelCase : Tuple = max_resolution _lowerCAmelCase : Optional[int] = do_resize_and_center_crop _lowerCAmelCase : Dict = size _lowerCAmelCase : int = crop_pct _lowerCAmelCase : Optional[Any] = crop_size _lowerCAmelCase : Tuple = do_normalize _lowerCAmelCase : List[str] = image_mean _lowerCAmelCase : Optional[Any] = image_std def __A ( self ): return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = PoolFormerImageProcessor if is_vision_available() else None def __A ( self ): _lowerCAmelCase : Tuple = PoolFormerImageProcessingTester(self ) @property def __A ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ): _lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a__ , """do_resize_and_center_crop""" ) ) self.assertTrue(hasattr(a__ , """size""" ) ) self.assertTrue(hasattr(a__ , """crop_pct""" ) ) self.assertTrue(hasattr(a__ , """do_normalize""" ) ) self.assertTrue(hasattr(a__ , """image_mean""" ) ) self.assertTrue(hasattr(a__ , """image_std""" ) ) def __A ( self ): _lowerCAmelCase : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 30} ) self.assertEqual(image_processor.crop_size , {"""height""": 30, """width""": 30} ) _lowerCAmelCase : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def __A ( self ): pass def __A ( self ): # Initialize image_processing _lowerCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ ) for image in image_inputs: self.assertIsInstance(a__ , Image.Image ) # Test not batched input _lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _lowerCAmelCase : str = image_processing(a__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def __A ( self ): # Initialize image_processing _lowerCAmelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , numpify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , np.ndarray ) # Test not batched input _lowerCAmelCase : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _lowerCAmelCase : List[Any] = image_processing(a__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def __A ( self ): # Initialize image_processing _lowerCAmelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase : Dict = 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 _lowerCAmelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _lowerCAmelCase : Any = image_processing(a__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
44
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Dict = parent _lowerCAmelCase : str = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Dict = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Any = hidden_dropout_prob _lowerCAmelCase : List[str] = attention_probs_dropout_prob _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : Tuple = type_sequence_label_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Tuple = relative_attention _lowerCAmelCase : Tuple = position_biased_input _lowerCAmelCase : Dict = pos_att_type _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCAmelCase : str = None if self.use_token_type_ids: _lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return 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 , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self , a__ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] _lowerCAmelCase : List[Any] = model(a__ , token_type_ids=a__ )[0] _lowerCAmelCase : Any = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = DebertaVaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : int = self.num_labels _lowerCAmelCase : int = DebertaVaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = DebertaVaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = DebertaVaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _UpperCamelCase : str = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = True _UpperCamelCase : List[Any] = False _UpperCamelCase : List[Any] = False _UpperCamelCase : Dict = False _UpperCamelCase : Tuple = False def __A ( self ): _lowerCAmelCase : Optional[Any] = DebertaVaModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*a__ ) @slow def __A ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Tuple = DebertaVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def __A ( self ): pass @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) _lowerCAmelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _lowerCAmelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. _lowerCAmelCase : str = torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F"{output[:, 1:4, 1:4]}" )
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any]=28123 ) -> Dict: _lowerCAmelCase : List[str] = [1] * (limit + 1) for i in range(2 ,int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 ,limit // i + 1 ): sum_divs[k * i] += k + i _lowerCAmelCase : List[Any] = set() _lowerCAmelCase : Tuple = 0 for n in range(1 ,limit + 1 ): if sum_divs[n] > n: abundants.add(_lowerCamelCase ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
44
"""simple docstring""" import numpy as np import qiskit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 8 ,_lowerCamelCase : int | None = None ) -> str: _lowerCAmelCase : int = np.random.default_rng(seed=_lowerCamelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. _lowerCAmelCase : Dict = rng.integers(2 ,size=_lowerCamelCase ) # The set of states Alice will prepare. _lowerCAmelCase : Tuple = rng.integers(2 ,size=_lowerCamelCase ) # Measurement basis for Bob's qubits. _lowerCAmelCase : Union[str, Any] = rng.integers(2 ,size=_lowerCamelCase ) # Quantum Circuit to simulate BB84 _lowerCAmelCase : Dict = qiskit.QuantumCircuit(_lowerCamelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCamelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCAmelCase : int = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCAmelCase : List[str] = qiskit.execute(_lowerCamelCase ,_lowerCamelCase ,shots=1 ,seed_simulator=_lowerCamelCase ) # Returns the result of measurement. _lowerCAmelCase : List[Any] = job.result().get_counts(_lowerCamelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCAmelCase : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCAmelCase : List[Any] = gen_key[:key_len] if len(_lowerCamelCase ) >= key_len else gen_key.ljust(_lowerCamelCase ,"""0""" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
44
1
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __A : _UpperCamelCase : List[str] _UpperCamelCase : Optional[str] = None # Automatically constructed _UpperCamelCase : ClassVar[str] = "dict" _UpperCamelCase : ClassVar[Any] = None _UpperCamelCase : str = field(default="Translation" , init=SCREAMING_SNAKE_CASE_ , repr=SCREAMING_SNAKE_CASE_ ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __A ( self ): from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class __A : _UpperCamelCase : Optional[List] = None _UpperCamelCase : Optional[int] = None _UpperCamelCase : Optional[str] = None # Automatically constructed _UpperCamelCase : ClassVar[str] = "dict" _UpperCamelCase : ClassVar[Any] = None _UpperCamelCase : str = field(default="TranslationVariableLanguages" , init=SCREAMING_SNAKE_CASE_ , repr=SCREAMING_SNAKE_CASE_ ) def __A ( self ): _lowerCAmelCase : str = sorted(set(self.languages ) ) if self.languages else None _lowerCAmelCase : Tuple = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def __A ( self , a__ ): _lowerCAmelCase : Any = set(self.languages ) if self.languages and set(a__ ) - lang_set: raise ValueError( F"Some languages in example ({', '.join(sorted(set(a__ ) - lang_set ) )}) are not in valid set ({', '.join(a__ )})." ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. _lowerCAmelCase : Optional[int] = [] for lang, text in translation_dict.items(): if isinstance(a__ , a__ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. _lowerCAmelCase , _lowerCAmelCase : List[str] = zip(*sorted(a__ ) ) return {"language": languages, "translation": translations} def __A ( self ): from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
44
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _a : Union[str, Any] = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _a : List[str] = 10 _a : List[Any] = 256 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[MinHash]: if len(_lowerCamelCase ) < MIN_NUM_TOKENS: return None _lowerCAmelCase : Optional[Any] = MinHash(num_perm=_lowerCamelCase ) for token in set(_lowerCamelCase ): min_hash.update(token.encode() ) return min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> Set[str]: return {t for t in NON_ALPHA.split(_lowerCamelCase ) if len(t.strip() ) > 0} class __A : def __init__( self , *, a__ = 0.8_5 , ): _lowerCAmelCase : List[Any] = duplication_jaccard_threshold _lowerCAmelCase : Union[str, Any] = NUM_PERM _lowerCAmelCase : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase : Optional[int] = defaultdict(a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[Any] = self._index.query(a__ ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(a__ , a__ ) if len(a__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(a__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(a__ ) def __A ( self ): _lowerCAmelCase : int = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase : List[str] = [base] + list(a__ ) # reformat the cluster to be a list of dict _lowerCAmelCase : List[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(a__ ) return duplicate_clusters def __A ( self , a__ ): _lowerCAmelCase : Dict = self.get_duplicate_clusters() with open(a__ , """w""" ) as f: json.dump(a__ , a__ ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : Tuple = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ) -> Optional[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash ,ThreadedIterator(_lowerCamelCase ,max_queue_size=10000 ) ,chunksize=100 ,): if data is not None: yield data def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float ) -> List[str]: _lowerCAmelCase : Optional[Any] = DuplicationIndex(duplication_jaccard_threshold=_lowerCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_lowerCamelCase ) ) ,max_queue_size=100 ) ): di.add(_lowerCamelCase ,_lowerCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> float: _lowerCAmelCase : Any = get_tokens(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = get_tokens(_lowerCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _a : str = None def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : List[Any] ) -> Dict: _lowerCAmelCase : int = [] for elementa in cluster: _lowerCAmelCase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: _lowerCAmelCase : Any = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(_lowerCamelCase ,_lowerCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase : Any = 1 extremes.append(_lowerCamelCase ) return extremes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Any ) -> str: global _shared_dataset _lowerCAmelCase : Tuple = dataset _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Optional[Any] = partial(_find_cluster_extremes_shared ,jaccard_threshold=_lowerCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _lowerCamelCase ,_lowerCamelCase ,) ,total=len(_lowerCamelCase ) ,): extremes_list.append(_lowerCamelCase ) return extremes_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase : Tuple = make_duplicate_clusters(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase : Optional[int] = {} _lowerCAmelCase : Tuple = find_extremes(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : List[Any] = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase : List[Any] = dataset.filter(lambda _lowerCamelCase ,_lowerCamelCase : idx not in remove_indices ,with_indices=_lowerCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase : Tuple = element["""base_index"""] in extreme_dict if element["is_extreme"]: _lowerCAmelCase : Dict = extreme_dict[element["""base_index"""]]["""copies"""] print(f"Original dataset size: {len(_lowerCamelCase )}" ) print(f"Number of duplicate clusters: {len(_lowerCamelCase )}" ) print(f"Files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Filtered dataset size: {len(_lowerCamelCase )}" ) return ds_filter, duplicate_clusters
44
1
"""simple docstring""" _a : Union[str, Any] = '0.21.0' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
44
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
1
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva _a : List[str] = '' _a : str = '' _a : Optional[Any] = '' _a : str = 1 # (0 is vertical, 1 is horizontal) def SCREAMING_SNAKE_CASE ( ) -> None: _lowerCAmelCase , _lowerCAmelCase : List[str] = get_dataset(_lowerCamelCase ,_lowerCamelCase ) print("""Processing...""" ) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = update_image_and_anno(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for index, image in enumerate(_lowerCamelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _lowerCAmelCase : Optional[Any] = random_chars(32 ) _lowerCAmelCase : Dict = paths[index].split(os.sep )[-1].rsplit(""".""" ,1 )[0] _lowerCAmelCase : Union[str, Any] = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cva.imwrite(f"/{file_root}.jpg" ,_lowerCamelCase ,[cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"Success {index+1}/{len(_lowerCamelCase )} with {file_name}" ) _lowerCAmelCase : str = [] for anno in new_annos[index]: _lowerCAmelCase : Optional[Any] = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(_lowerCamelCase ) with open(f"/{file_root}.txt" ,"""w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> tuple[list, list]: _lowerCAmelCase : Dict = [] _lowerCAmelCase : Tuple = [] for label_file in glob.glob(os.path.join(_lowerCamelCase ,"""*.txt""" ) ): _lowerCAmelCase : Dict = label_file.split(os.sep )[-1].rsplit(""".""" ,1 )[0] with open(_lowerCamelCase ) as in_file: _lowerCAmelCase : List[Any] = in_file.readlines() _lowerCAmelCase : int = os.path.join(_lowerCamelCase ,f"{label_name}.jpg" ) _lowerCAmelCase : Optional[Any] = [] for obj_list in obj_lists: _lowerCAmelCase : Dict = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(_lowerCamelCase ) labels.append(_lowerCamelCase ) return img_paths, labels def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list ,_lowerCamelCase : list ,_lowerCamelCase : int = 1 ) -> tuple[list, list, list]: _lowerCAmelCase : int = [] _lowerCAmelCase : str = [] _lowerCAmelCase : Optional[int] = [] for idx in range(len(_lowerCamelCase ) ): _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Any = img_list[idx] path_list.append(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = anno_list[idx] _lowerCAmelCase : int = cva.imread(_lowerCamelCase ) if flip_type == 1: _lowerCAmelCase : int = cva.flip(_lowerCamelCase ,_lowerCamelCase ) for bbox in img_annos: _lowerCAmelCase : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: _lowerCAmelCase : str = cva.flip(_lowerCamelCase ,_lowerCamelCase ) for bbox in img_annos: _lowerCAmelCase : Union[str, Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(_lowerCamelCase ) new_imgs_list.append(_lowerCamelCase ) return new_imgs_list, new_annos_lists, path_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" _lowerCAmelCase : Optional[int] = ascii_lowercase + digits return "".join(random.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) if __name__ == "__main__": main() print('DONE ✅')
44
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
1
"""simple docstring""" import os import sys _a : List[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) _a : Optional[Any] = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : List[str] ,**_lowerCamelCase : Optional[Any] ) -> Any: return AutoConfig.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : List[str] ,**_lowerCamelCase : int ) -> List[str]: return AutoTokenizer.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : Any ,**_lowerCamelCase : str ) -> Any: return AutoModel.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : List[str] ,**_lowerCamelCase : List[Any] ) -> Dict: return AutoModelForCausalLM.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : List[Any] ,**_lowerCamelCase : Optional[int] ) -> Union[str, Any]: return AutoModelForMaskedLM.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : List[Any] ,**_lowerCamelCase : Dict ) -> Dict: return AutoModelForSequenceClassification.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE ( *_lowerCamelCase : Union[str, Any] ,**_lowerCamelCase : List[Any] ) -> Optional[Any]: return AutoModelForQuestionAnswering.from_pretrained(*_lowerCamelCase ,**_lowerCamelCase )
44
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : List[Any] = torch.exp(_lowerCamelCase ) _lowerCAmelCase : List[Any] = torch.sum(_lowerCamelCase ,dim=1 ) # sum of exp(x_i) _lowerCAmelCase : Dict = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : int = config.output_attentions _lowerCAmelCase : Any = config.output_hidden_states _lowerCAmelCase : List[Any] = nn.ModuleList([BertLayer(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : Any = nn.ModuleList([BertHighway(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : str = [-1 for _ in range(config.num_hidden_layers )] def __A ( self , a__ ): if (type(a__ ) is float) or (type(a__ ) is int): for i in range(len(self.early_exit_entropy ) ): _lowerCAmelCase : Tuple = x else: _lowerCAmelCase : Optional[int] = x def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __A ( self , a__ , a__=None , a__=None , a__=None , a__=None , ): _lowerCAmelCase : Any = () _lowerCAmelCase : Optional[int] = () _lowerCAmelCase : List[Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _lowerCAmelCase : str = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[str] = layer_module( a__ , a__ , head_mask[i] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = layer_outputs[0] if self.output_attentions: _lowerCAmelCase : Dict = all_attentions + (layer_outputs[1],) _lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Optional[int] = current_outputs + (all_attentions,) _lowerCAmelCase : Optional[Any] = self.highway[i](a__ ) # logits, pooled_output if not self.training: _lowerCAmelCase : Tuple = highway_exit[0] _lowerCAmelCase : Any = entropy(a__ ) _lowerCAmelCase : Optional[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _lowerCAmelCase : Union[str, Any] = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _lowerCAmelCase : List[str] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a__ , i + 1 ) else: _lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _lowerCAmelCase : List[Any] = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[Any] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : List[str] = outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Any = outputs + (all_attentions,) _lowerCAmelCase : Optional[int] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config _lowerCAmelCase : Tuple = BertEmbeddings(a__ ) _lowerCAmelCase : Tuple = DeeBertEncoder(a__ ) _lowerCAmelCase : List[str] = BertPooler(a__ ) self.init_weights() def __A ( self ): self.encoder.init_highway_pooler(self.pooler ) def __A ( self ): return self.embeddings.word_embeddings def __A ( self , a__ ): _lowerCAmelCase : Dict = value def __A ( self , a__ ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a__ ) @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _lowerCAmelCase : Any = input_ids.size() elif inputs_embeds is not None: _lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _lowerCAmelCase : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _lowerCAmelCase : List[Any] = torch.ones(a__ , device=a__ ) if encoder_attention_mask is None: _lowerCAmelCase : Optional[Any] = torch.ones(a__ , device=a__ ) if token_type_ids is None: _lowerCAmelCase : Dict = torch.zeros(a__ , dtype=torch.long , device=a__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(a__ , a__ , a__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _lowerCAmelCase : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _lowerCAmelCase : Tuple = encoder_attention_mask[:, None, None, :] _lowerCAmelCase : Union[str, Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _lowerCAmelCase : Optional[Any] = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _lowerCAmelCase : Optional[int] = self.get_head_mask(a__ , self.config.num_hidden_layers ) _lowerCAmelCase : Dict = self.embeddings( input_ids=a__ , position_ids=a__ , token_type_ids=a__ , inputs_embeds=a__ ) _lowerCAmelCase : Union[str, Any] = self.encoder( a__ , attention_mask=a__ , head_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Dict = encoder_outputs[0] _lowerCAmelCase : Union[str, Any] = self.pooler(a__ ) _lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ ): _lowerCAmelCase : str = message _lowerCAmelCase : str = exit_layer # start from 1! class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Any = BertPooler(a__ ) _lowerCAmelCase : str = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def __A ( self , a__ ): # Pooler _lowerCAmelCase : Tuple = encoder_outputs[0] _lowerCAmelCase : int = self.pooler(a__ ) # "return" pooler_output # BertModel _lowerCAmelCase : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _lowerCAmelCase : Optional[int] = bmodel_output[1] _lowerCAmelCase : Tuple = self.dropout(a__ ) _lowerCAmelCase : Dict = self.classifier(a__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[str] = config.num_labels _lowerCAmelCase : Optional[Any] = config.num_hidden_layers _lowerCAmelCase : str = DeeBertModel(a__ ) _lowerCAmelCase : Tuple = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : List[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=-1 , a__=False , ): _lowerCAmelCase : Dict = self.num_layers try: _lowerCAmelCase : str = self.bert( a__ , attention_mask=a__ , token_type_ids=a__ , position_ids=a__ , head_mask=a__ , inputs_embeds=a__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _lowerCAmelCase : Any = outputs[1] _lowerCAmelCase : Optional[int] = self.dropout(a__ ) _lowerCAmelCase : List[str] = self.classifier(a__ ) _lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : int = e.exit_layer _lowerCAmelCase : Union[str, Any] = outputs[0] if not self.training: _lowerCAmelCase : Tuple = entropy(a__ ) _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Tuple = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase : Optional[Any] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Dict = highway_exit[0] if not self.training: highway_logits_all.append(a__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Optional[int] = CrossEntropyLoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(a__ ) if train_highway: _lowerCAmelCase : List[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Dict = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Dict = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[Any]: stooge(_lowerCamelCase ,0 ,len(_lowerCamelCase ) - 1 ) return arr def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : List[str] ,_lowerCamelCase : Any ) -> str: if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _lowerCAmelCase , _lowerCAmelCase : str = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _lowerCAmelCase : int = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(_lowerCamelCase ,_lowerCamelCase ,(h - t) ) # Recursively sort last 2/3 elements stooge(_lowerCamelCase ,i + t ,(_lowerCamelCase) ) # Recursively sort first 2/3 elements stooge(_lowerCamelCase ,_lowerCamelCase ,(h - t) ) if __name__ == "__main__": _a : List[str] = input('Enter numbers separated by a comma:\n').strip() _a : List[Any] = [int(item) for item in user_input.split(',')] print(stooge_sort(unsorted))
44
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : str = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , a__ = None , a__ = None , **a__ , ): super().__init__(self , **a__ ) _lowerCAmelCase : Any = repo_info _lowerCAmelCase : Optional[Any] = token _lowerCAmelCase : Optional[int] = None def __A ( self ): if self.dir_cache is None: _lowerCAmelCase : Optional[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowerCAmelCase : 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 __A ( self , a__ , a__ = "rb" , **a__ , ): if not isinstance(self.repo_info , a__ ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) _lowerCAmelCase : Tuple = 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 __A ( self , a__ , **a__ ): self._get_dirs() _lowerCAmelCase : Union[str, Any] = self._strip_protocol(a__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a__ ) def __A ( self , a__ , a__=False , **a__ ): self._get_dirs() _lowerCAmelCase : Any = PurePosixPath(path.strip("""/""" ) ) _lowerCAmelCase : List[str] = {} for p, f in self.dir_cache.items(): _lowerCAmelCase : Any = PurePosixPath(p.strip("""/""" ) ) _lowerCAmelCase : Optional[int] = p.parent if root == path: _lowerCAmelCase : Dict = f _lowerCAmelCase : Union[str, Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
44
1
"""simple docstring""" import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : List[str]="shi-labs/oneformer_demo" ) -> List[str]: with open(hf_hub_download(_lowerCamelCase ,_lowerCamelCase ,repo_type="""dataset""" ) ,"""r""" ) as f: _lowerCAmelCase : Tuple = json.load(_lowerCamelCase ) _lowerCAmelCase : str = {} _lowerCAmelCase : Dict = [] _lowerCAmelCase : Any = [] for key, info in class_info.items(): _lowerCAmelCase : Tuple = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(_lowerCamelCase ) ) _lowerCAmelCase : int = thing_ids _lowerCAmelCase : List[str] = class_names return metadata class __A ( unittest.TestCase ): def __init__( self , a__ , a__=7 , a__=3 , a__=30 , a__=400 , a__=None , a__=True , a__=True , a__=[0.5, 0.5, 0.5] , a__=[0.5, 0.5, 0.5] , a__=10 , a__=False , a__=255 , a__="shi-labs/oneformer_demo" , a__="ade20k_panoptic.json" , a__=10 , ): _lowerCAmelCase : Optional[Any] = parent _lowerCAmelCase : Optional[Any] = batch_size _lowerCAmelCase : str = num_channels _lowerCAmelCase : str = min_resolution _lowerCAmelCase : int = max_resolution _lowerCAmelCase : Any = do_resize _lowerCAmelCase : Optional[int] = {"""shortest_edge""": 32, """longest_edge""": 1333} if size is None else size _lowerCAmelCase : List[str] = do_normalize _lowerCAmelCase : Dict = image_mean _lowerCAmelCase : Any = image_std _lowerCAmelCase : Dict = class_info_file _lowerCAmelCase : Tuple = prepare_metadata(a__ , a__ ) _lowerCAmelCase : Optional[int] = num_text _lowerCAmelCase : int = repo_path # for the post_process_functions _lowerCAmelCase : Any = 2 _lowerCAmelCase : int = 10 _lowerCAmelCase : List[str] = 10 _lowerCAmelCase : Optional[int] = 3 _lowerCAmelCase : Any = 4 _lowerCAmelCase : Optional[int] = num_labels _lowerCAmelCase : List[Any] = do_reduce_labels _lowerCAmelCase : Dict = ignore_index def __A ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def __A ( self , a__ , a__=False ): if not batched: _lowerCAmelCase : Any = image_inputs[0] if isinstance(a__ , Image.Image ): _lowerCAmelCase , _lowerCAmelCase : Tuple = image.size else: _lowerCAmelCase , _lowerCAmelCase : List[str] = image.shape[1], image.shape[2] if w < h: _lowerCAmelCase : str = int(self.size["""shortest_edge"""] * h / w ) _lowerCAmelCase : List[str] = self.size["""shortest_edge"""] elif w > h: _lowerCAmelCase : Optional[int] = self.size["""shortest_edge"""] _lowerCAmelCase : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h ) else: _lowerCAmelCase : Dict = self.size["""shortest_edge"""] _lowerCAmelCase : List[Any] = self.size["""shortest_edge"""] else: _lowerCAmelCase : List[Any] = [] for image in image_inputs: _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _lowerCAmelCase : Tuple = max(a__ , key=lambda a__ : item[0] )[0] _lowerCAmelCase : Union[str, Any] = max(a__ , key=lambda a__ : item[1] )[1] return expected_height, expected_width def __A ( self ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Dict = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string _UpperCamelCase : List[str] = image_processing_class def __A ( self ): _lowerCAmelCase : int = OneFormerImageProcessorTester(self ) @property def __A ( self ): return self.image_processing_tester.prepare_image_processor_dict() def __A ( self ): _lowerCAmelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a__ , """image_mean""" ) ) self.assertTrue(hasattr(a__ , """image_std""" ) ) self.assertTrue(hasattr(a__ , """do_normalize""" ) ) self.assertTrue(hasattr(a__ , """do_resize""" ) ) self.assertTrue(hasattr(a__ , """size""" ) ) self.assertTrue(hasattr(a__ , """ignore_index""" ) ) self.assertTrue(hasattr(a__ , """class_info_file""" ) ) self.assertTrue(hasattr(a__ , """num_text""" ) ) self.assertTrue(hasattr(a__ , """repo_path""" ) ) self.assertTrue(hasattr(a__ , """metadata""" ) ) self.assertTrue(hasattr(a__ , """do_reduce_labels""" ) ) def __A ( self ): pass def __A ( self ): # Initialize image_processor _lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase : Optional[int] = prepare_image_inputs(self.image_processing_tester , equal_resolution=a__ ) for image in image_inputs: self.assertIsInstance(a__ , Image.Image ) # Test not batched input _lowerCAmelCase : int = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.image_processing_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase , _lowerCAmelCase : str = self.image_processing_tester.get_expected_values(a__ , batched=a__ ) _lowerCAmelCase : Any = image_processor( a__ , ["""semantic"""] * len(a__ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ): # Initialize image_processor _lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase : Optional[int] = prepare_image_inputs(self.image_processing_tester , equal_resolution=a__ , numpify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , np.ndarray ) # Test not batched input _lowerCAmelCase : Tuple = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.image_processing_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.image_processing_tester.get_expected_values(a__ , batched=a__ ) _lowerCAmelCase : Optional[Any] = image_processor( a__ , ["""semantic"""] * len(a__ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ): # Initialize image_processor _lowerCAmelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase : int = prepare_image_inputs(self.image_processing_tester , equal_resolution=a__ , torchify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , torch.Tensor ) # Test not batched input _lowerCAmelCase : Union[str, Any] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.image_processing_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase , _lowerCAmelCase : str = self.image_processing_tester.get_expected_values(a__ , batched=a__ ) _lowerCAmelCase : Optional[Any] = image_processor( a__ , ["""semantic"""] * len(a__ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self , a__=False , a__=False , a__="np" ): _lowerCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target _lowerCAmelCase : Any = self.image_processing_tester.num_labels _lowerCAmelCase : List[str] = None _lowerCAmelCase : List[str] = None _lowerCAmelCase : List[str] = prepare_image_inputs(self.image_processing_tester , equal_resolution=a__ ) if with_segmentation_maps: _lowerCAmelCase : Tuple = num_labels if is_instance_map: _lowerCAmelCase : Optional[int] = list(range(a__ ) ) * 2 _lowerCAmelCase : Optional[int] = dict(enumerate(a__ ) ) _lowerCAmelCase : int = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": _lowerCAmelCase : Optional[int] = [Image.fromarray(a__ ) for annotation in annotations] _lowerCAmelCase : Union[str, Any] = image_processor( a__ , ["""semantic"""] * len(a__ ) , a__ , return_tensors="""pt""" , instance_id_to_semantic_id=a__ , pad_and_return_pixel_mask=a__ , ) return inputs def __A ( self ): pass def __A ( self ): def common(a__=False , a__=None ): _lowerCAmelCase : str = self.comm_get_image_processor_inputs( with_segmentation_maps=a__ , is_instance_map=a__ , segmentation_type=a__ ) _lowerCAmelCase : List[Any] = inputs["""mask_labels"""] _lowerCAmelCase : Any = inputs["""class_labels"""] _lowerCAmelCase : Tuple = inputs["""pixel_values"""] _lowerCAmelCase : Any = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(a__ , a__ , a__ ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(a__ ) , self.image_processing_tester.num_text ) common() common(is_instance_map=a__ ) common(is_instance_map=a__ , segmentation_type="""pil""" ) common(is_instance_map=a__ , segmentation_type="""pil""" ) def __A ( self ): _lowerCAmelCase : Any = np.zeros((20, 50) ) _lowerCAmelCase : Any = 1 _lowerCAmelCase : Dict = 1 _lowerCAmelCase : Union[str, Any] = 1 _lowerCAmelCase : Optional[int] = binary_mask_to_rle(a__ ) self.assertEqual(len(a__ ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def __A ( self ): _lowerCAmelCase : Optional[int] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) _lowerCAmelCase : Any = self.image_processing_tester.get_fake_oneformer_outputs() _lowerCAmelCase : Tuple = fature_extractor.post_process_semantic_segmentation(a__ ) self.assertEqual(len(a__ ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) _lowerCAmelCase : Tuple = [(1, 4) for i in range(self.image_processing_tester.batch_size )] _lowerCAmelCase : Union[str, Any] = fature_extractor.post_process_semantic_segmentation(a__ , target_sizes=a__ ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def __A ( self ): _lowerCAmelCase : Any = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) _lowerCAmelCase : List[Any] = self.image_processing_tester.get_fake_oneformer_outputs() _lowerCAmelCase : Union[str, Any] = image_processor.post_process_instance_segmentation(a__ , threshold=0 ) self.assertTrue(len(a__ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , a__ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def __A ( self ): _lowerCAmelCase : List[str] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) _lowerCAmelCase : Dict = self.image_processing_tester.get_fake_oneformer_outputs() _lowerCAmelCase : Any = image_processor.post_process_panoptic_segmentation(a__ , threshold=0 ) self.assertTrue(len(a__ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , a__ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
44
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_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""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): 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 __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _a : Optional[int] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _a : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
1
"""simple docstring""" import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() _a : Optional[int] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : str ,_lowerCamelCase : List[str] ) -> int: _lowerCAmelCase : List[str] = os.path.abspath(_lowerCamelCase ) logger.info(f"Converting TensorFlow checkpoint from {tf_path}" ) # Load weights from TF model _lowerCAmelCase : int = tf.train.list_variables(_lowerCamelCase ) _lowerCAmelCase : List[Any] = [] _lowerCAmelCase : Tuple = [] _lowerCAmelCase : Optional[int] = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") _lowerCAmelCase : Dict = full_name.split("""/""" ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f"Skipping non-model layer {full_name}" ) continue if "optimizer" in full_name: logger.info(f"Skipping optimization layer {full_name}" ) continue if name[0] == "model": # ignore initial 'model' _lowerCAmelCase : Dict = name[1:] # figure out how many levels deep the name is _lowerCAmelCase : Optional[Any] = 0 for _name in name: if _name.startswith("""layer_with_weights""" ): depth += 1 else: break layer_depth.append(_lowerCamelCase ) # read data _lowerCAmelCase : List[Any] = tf.train.load_variable(_lowerCamelCase ,_lowerCamelCase ) names.append("""/""".join(_lowerCamelCase ) ) arrays.append(_lowerCamelCase ) logger.info(f"Read a total of {len(_lowerCamelCase ):,} layers" ) # Sanity check if len(set(_lowerCamelCase ) ) != 1: raise ValueError(f"Found layer names with different depths (layer depth {list(set(_lowerCamelCase ) )})" ) _lowerCAmelCase : Union[str, Any] = list(set(_lowerCamelCase ) )[0] if layer_depth != 1: raise ValueError( """The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP""" """ heads.""" ) # convert layers logger.info("""Converting weights...""" ) for full_name, array in zip(_lowerCamelCase ,_lowerCamelCase ): _lowerCAmelCase : Optional[Any] = full_name.split("""/""" ) _lowerCAmelCase : str = model _lowerCAmelCase : Optional[int] = [] for i, m_name in enumerate(_lowerCamelCase ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith("""layer_with_weights""" ): _lowerCAmelCase : Dict = int(m_name.split("""-""" )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(["""embeddings""", """LayerNorm"""] ) _lowerCAmelCase : int = getattr(_lowerCamelCase ,"""embeddings""" ) _lowerCAmelCase : List[Any] = getattr(_lowerCamelCase ,"""LayerNorm""" ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(["""encoder""", """layer""", str(layer_num - 4 )] ) _lowerCAmelCase : int = getattr(_lowerCamelCase ,"""encoder""" ) _lowerCAmelCase : Optional[int] = getattr(_lowerCamelCase ,"""layer""" ) _lowerCAmelCase : List[Any] = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(["""pooler""", """dense"""] ) _lowerCAmelCase : int = getattr(_lowerCamelCase ,"""pooler""" ) _lowerCAmelCase : Optional[Any] = getattr(_lowerCamelCase ,"""dense""" ) elif m_name == "embeddings": trace.append("""embeddings""" ) _lowerCAmelCase : Tuple = getattr(_lowerCamelCase ,"""embeddings""" ) if layer_num == 0: trace.append("""word_embeddings""" ) _lowerCAmelCase : Optional[int] = getattr(_lowerCamelCase ,"""word_embeddings""" ) elif layer_num == 1: trace.append("""position_embeddings""" ) _lowerCAmelCase : List[Any] = getattr(_lowerCamelCase ,"""position_embeddings""" ) elif layer_num == 2: trace.append("""token_type_embeddings""" ) _lowerCAmelCase : str = getattr(_lowerCamelCase ,"""token_type_embeddings""" ) else: raise ValueError(f"Unknown embedding layer with name {full_name}" ) trace.append("""weight""" ) _lowerCAmelCase : Dict = getattr(_lowerCamelCase ,"""weight""" ) elif m_name == "_attention_layer": # self-attention layer trace.extend(["""attention""", """self"""] ) _lowerCAmelCase : Tuple = getattr(_lowerCamelCase ,"""attention""" ) _lowerCAmelCase : str = getattr(_lowerCamelCase ,"""self""" ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(["""attention""", """output""", """LayerNorm"""] ) _lowerCAmelCase : List[str] = getattr(_lowerCamelCase ,"""attention""" ) _lowerCAmelCase : Tuple = getattr(_lowerCamelCase ,"""output""" ) _lowerCAmelCase : Dict = getattr(_lowerCamelCase ,"""LayerNorm""" ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(["""attention""", """output""", """dense"""] ) _lowerCAmelCase : int = getattr(_lowerCamelCase ,"""attention""" ) _lowerCAmelCase : int = getattr(_lowerCamelCase ,"""output""" ) _lowerCAmelCase : List[Any] = getattr(_lowerCamelCase ,"""dense""" ) elif m_name == "_output_dense": # output dense trace.extend(["""output""", """dense"""] ) _lowerCAmelCase : List[str] = getattr(_lowerCamelCase ,"""output""" ) _lowerCAmelCase : Any = getattr(_lowerCamelCase ,"""dense""" ) elif m_name == "_output_layer_norm": # output dense trace.extend(["""output""", """LayerNorm"""] ) _lowerCAmelCase : Tuple = getattr(_lowerCamelCase ,"""output""" ) _lowerCAmelCase : List[str] = getattr(_lowerCamelCase ,"""LayerNorm""" ) elif m_name == "_key_dense": # attention key trace.append("""key""" ) _lowerCAmelCase : str = getattr(_lowerCamelCase ,"""key""" ) elif m_name == "_query_dense": # attention query trace.append("""query""" ) _lowerCAmelCase : Optional[int] = getattr(_lowerCamelCase ,"""query""" ) elif m_name == "_value_dense": # attention value trace.append("""value""" ) _lowerCAmelCase : Optional[Any] = getattr(_lowerCamelCase ,"""value""" ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(["""intermediate""", """dense"""] ) _lowerCAmelCase : str = getattr(_lowerCamelCase ,"""intermediate""" ) _lowerCAmelCase : Optional[Any] = getattr(_lowerCamelCase ,"""dense""" ) elif m_name == "_output_layer_norm": # output layer norm trace.append("""output""" ) _lowerCAmelCase : Any = getattr(_lowerCamelCase ,"""output""" ) # weights & biases elif m_name in ["bias", "beta"]: trace.append("""bias""" ) _lowerCAmelCase : List[str] = getattr(_lowerCamelCase ,"""bias""" ) elif m_name in ["kernel", "gamma"]: trace.append("""weight""" ) _lowerCAmelCase : str = getattr(_lowerCamelCase ,"""weight""" ) else: logger.warning(f"Ignored {m_name}" ) # for certain layers reshape is necessary _lowerCAmelCase : Any = """.""".join(_lowerCamelCase ) if re.match(r"""(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)""" ,_lowerCamelCase ) or re.match( r"""(\S+)\.attention\.output\.dense\.weight""" ,_lowerCamelCase ): _lowerCAmelCase : str = array.reshape(pointer.data.shape ) if "kernel" in full_name: _lowerCAmelCase : Optional[int] = array.transpose() if pointer.shape == array.shape: _lowerCAmelCase : Optional[int] = torch.from_numpy(_lowerCamelCase ) else: raise ValueError( f"Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:" f" {array.shape}" ) logger.info(f"Successfully set variable {full_name} to PyTorch layer {trace}" ) return model def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ,_lowerCamelCase : Any ) -> Tuple: # Instantiate model logger.info(f"Loading model based on config from {config_path}..." ) _lowerCAmelCase : List[Any] = BertConfig.from_json_file(_lowerCamelCase ) _lowerCAmelCase : Tuple = BertModel(_lowerCamelCase ) # Load weights from checkpoint logger.info(f"Loading weights from checkpoint {tf_checkpoint_path}..." ) load_tfa_weights_in_bert(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) # Save pytorch-model logger.info(f"Saving PyTorch model to {pytorch_dump_path}..." ) torch.save(model.state_dict() ,_lowerCamelCase ) if __name__ == "__main__": _a : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow 2.x checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model (must include filename).', ) _a : List[str] = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
44
"""simple docstring""" _a : List[str] = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.13.2', 'requests-mock': 'requests-mock==1.10.0', 'importlib_metadata': 'importlib_metadata', 'invisible-watermark': 'invisible-watermark', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2', 'jaxlib': 'jaxlib>=0.1.65', 'Jinja2': 'Jinja2', 'k-diffusion': 'k-diffusion>=0.0.12', 'torchsde': 'torchsde', 'note_seq': 'note_seq', 'librosa': 'librosa', 'numpy': 'numpy', 'omegaconf': 'omegaconf', 'parameterized': 'parameterized', 'protobuf': 'protobuf>=3.20.3,<4', 'pytest': 'pytest', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'ruff': 'ruff>=0.0.241', 'safetensors': 'safetensors', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'scipy': 'scipy', 'onnx': 'onnx', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'tensorboard': 'tensorboard', 'torch': 'torch>=1.4', 'torchvision': 'torchvision', 'transformers': 'transformers>=4.25.1', 'urllib3': 'urllib3<=2.0.0', }
44
1
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class __A : @staticmethod def __A ( *a__ , **a__ ): pass def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Image ) -> str: _lowerCAmelCase : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Image ) -> Dict: _lowerCAmelCase : Dict = np.array(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = npimg.shape return {"hash": hashimage(_lowerCamelCase ), "shape": shape} @is_pipeline_test @require_vision @require_torch class __A ( unittest.TestCase ): _UpperCamelCase : Optional[Any] = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _UpperCamelCase : Union[str, Any] = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __A ( self , a__ , a__ ): pass @require_tf @unittest.skip("""Image segmentation not implemented in TF""" ) def __A ( self ): pass @slow @require_torch def __A ( self ): _lowerCAmelCase : Dict = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""" ) _lowerCAmelCase : Optional[int] = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=256 ) # Shortening by hashing _lowerCAmelCase : Dict = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_4_4_4}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0_2_1}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_1_6_7}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_1_3_2}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_0_5_3}, {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (480, 640)}, """scores""": 0.9_9_6_7}, {"""mask""": {"""hash""": """453c7844bd""", """shape""": (480, 640)}, """scores""": 0.9_9_3}, {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (480, 640)}, """scores""": 0.9_9_0_9}, {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (480, 640)}, """scores""": 0.9_8_7_9}, {"""mask""": {"""hash""": """801064ff79""", """shape""": (480, 640)}, """scores""": 0.9_8_3_4}, {"""mask""": {"""hash""": """6172f276ef""", """shape""": (480, 640)}, """scores""": 0.9_7_1_6}, {"""mask""": {"""hash""": """b49e60e084""", """shape""": (480, 640)}, """scores""": 0.9_6_1_2}, {"""mask""": {"""hash""": """a811e775fd""", """shape""": (480, 640)}, """scores""": 0.9_5_9_9}, {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (480, 640)}, """scores""": 0.9_5_5_2}, {"""mask""": {"""hash""": """9d8257e080""", """shape""": (480, 640)}, """scores""": 0.9_5_3_2}, {"""mask""": {"""hash""": """32de6454a8""", """shape""": (480, 640)}, """scores""": 0.9_5_1_6}, {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (480, 640)}, """scores""": 0.9_4_9_9}, {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (480, 640)}, """scores""": 0.9_4_8_3}, {"""mask""": {"""hash""": """c290813fb9""", """shape""": (480, 640)}, """scores""": 0.9_4_6_4}, {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (480, 640)}, """scores""": 0.9_4_3}, {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (480, 640)}, """scores""": 0.9_4_3}, {"""mask""": {"""hash""": """c749b25868""", """shape""": (480, 640)}, """scores""": 0.9_4_0_8}, {"""mask""": {"""hash""": """efb6cab859""", """shape""": (480, 640)}, """scores""": 0.9_3_3_5}, {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (480, 640)}, """scores""": 0.9_3_2_6}, {"""mask""": {"""hash""": """788b798e24""", """shape""": (480, 640)}, """scores""": 0.9_2_6_2}, {"""mask""": {"""hash""": """abea804f0e""", """shape""": (480, 640)}, """scores""": 0.8_9_9_9}, {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (480, 640)}, """scores""": 0.8_9_8_6}, {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (480, 640)}, """scores""": 0.8_9_8_4}, {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (480, 640)}, """scores""": 0.8_8_7_3}, {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (480, 640)}, """scores""": 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def __A ( self ): _lowerCAmelCase : Optional[int] = """facebook/sam-vit-huge""" _lowerCAmelCase : Any = pipeline("""mask-generation""" , model=a__ ) _lowerCAmelCase : Optional[int] = image_segmenter( """http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing _lowerCAmelCase : Tuple = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_4_4_4}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0_2_1_0}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_1_6_7}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_1_3_2}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_0_5_3}, ] , )
44
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _a : Dict = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , *a__ , **a__ ): super().__init__(*a__ , **a__ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , a__=None , a__=None , a__=None ): _lowerCAmelCase : List[str] = {} _lowerCAmelCase : Union[str, Any] = {} if prompt is not None: _lowerCAmelCase : List[Any] = prompt if generate_kwargs is not None: _lowerCAmelCase : List[str] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _lowerCAmelCase : str = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) _lowerCAmelCase : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , a__ , **a__ ): return super().__call__(a__ , **a__ ) def __A ( self , a__ , a__=None ): _lowerCAmelCase : Tuple = load_image(a__ ) if prompt is not None: if not isinstance(a__ , a__ ): raise ValueError( F"Received an invalid text input, got - {type(a__ )} - but expected a single string. " """Note also that one single text can be provided for conditional image to text generation.""" ) _lowerCAmelCase : Optional[int] = self.model.config.model_type if model_type == "git": _lowerCAmelCase : Optional[Any] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : List[str] = self.tokenizer(text=a__ , add_special_tokens=a__ ).input_ids _lowerCAmelCase : Union[str, Any] = [self.tokenizer.cls_token_id] + input_ids _lowerCAmelCase : Dict = torch.tensor(a__ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _lowerCAmelCase : Tuple = self.image_processor(images=a__ , header_text=a__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _lowerCAmelCase : Optional[int] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : Optional[int] = self.tokenizer(a__ , return_tensors=self.framework ) model_inputs.update(a__ ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: _lowerCAmelCase : Any = self.image_processor(images=a__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _lowerCAmelCase : Union[str, Any] = None return model_inputs def __A ( self , a__ , a__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , a__ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _lowerCAmelCase : Optional[int] = None if generate_kwargs is None: _lowerCAmelCase : List[str] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _lowerCAmelCase : Tuple = model_inputs.pop(self.model.main_input_name ) _lowerCAmelCase : Union[str, Any] = self.model.generate(a__ , **a__ , **a__ ) return model_outputs def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for output_ids in model_outputs: _lowerCAmelCase : Any = { """generated_text""": self.tokenizer.decode( a__ , skip_special_tokens=a__ , ) } records.append(a__ ) return records
44
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _a : Dict = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.BuilderConfig ): _UpperCamelCase : int = 10_000 _UpperCamelCase : Optional[List[str]] = None _UpperCamelCase : Optional[datasets.Features] = None class __A ( datasets.ArrowBasedBuilder ): _UpperCamelCase : List[str] = ParquetConfig def __A ( self ): return datasets.DatasetInfo(features=self.config.features ) def __A ( self , a__ ): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) _lowerCAmelCase : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): _lowerCAmelCase : Any = data_files if isinstance(a__ , a__ ): _lowerCAmelCase : Tuple = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Any = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] _lowerCAmelCase : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): _lowerCAmelCase : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Tuple = [dl_manager.iter_files(a__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(a__ ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(a__ ) ) break splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , a__ ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _lowerCAmelCase : Optional[int] = table_cast(a__ , self.info.features.arrow_schema ) return pa_table def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Tuple = pq.ParquetFile(a__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): _lowerCAmelCase : Any = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(a__ ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
44
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : Tuple = { 'configuration_wav2vec2': ['WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Wav2Vec2Config'], 'feature_extraction_wav2vec2': ['Wav2Vec2FeatureExtractor'], 'processing_wav2vec2': ['Wav2Vec2Processor'], 'tokenization_wav2vec2': ['Wav2Vec2CTCTokenizer', 'Wav2Vec2Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Any = [ 'WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Wav2Vec2ForAudioFrameClassification', 'Wav2Vec2ForCTC', 'Wav2Vec2ForMaskedLM', 'Wav2Vec2ForPreTraining', 'Wav2Vec2ForSequenceClassification', 'Wav2Vec2ForXVector', 'Wav2Vec2Model', 'Wav2Vec2PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWav2Vec2ForCTC', 'TFWav2Vec2Model', 'TFWav2Vec2PreTrainedModel', 'TFWav2Vec2ForSequenceClassification', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'FlaxWav2Vec2ForCTC', 'FlaxWav2Vec2ForPreTraining', 'FlaxWav2Vec2Model', 'FlaxWav2Vec2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys _a : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) _a : Tuple = logging.getLogger(__name__) _a : Any = {'facebook/bart-base': BartForConditionalGeneration} _a : List[str] = {'facebook/bart-base': BartTokenizer} def SCREAMING_SNAKE_CASE ( ) -> int: _lowerCAmelCase : int = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" ,type=_lowerCamelCase ,default=5 ,help="""The maximum total input sequence length after tokenization.""" ,) parser.add_argument( """--num_beams""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) ,) parser.add_argument( """--model_name_or_path""" ,type=_lowerCamelCase ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=_lowerCamelCase ,) parser.add_argument( """--config_name""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Pretrained config name or path if not the same as model_name""" ,) parser.add_argument( """--device""" ,type=_lowerCamelCase ,default="""cpu""" ,help="""Device where the model will be run""" ,) parser.add_argument("""--output_file_path""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Where to store the final ONNX file.""" ) _lowerCAmelCase : Optional[Any] = parser.parse_args() return args def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Union[str, Any]="cpu" ) -> str: _lowerCAmelCase : List[str] = model_dict[model_name].from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = tokenizer_dict[model_name].from_pretrained(_lowerCamelCase ) if model_name in ["facebook/bart-base"]: _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : str = None _lowerCAmelCase : List[str] = 0 return huggingface_model, tokenizer def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : List[str] ,_lowerCamelCase : int ,_lowerCamelCase : List[Any] ,_lowerCamelCase : List[str] ) -> Tuple: model.eval() _lowerCAmelCase : str = None _lowerCAmelCase : int = torch.jit.script(BARTBeamSearchGenerator(_lowerCamelCase ) ) with torch.no_grad(): _lowerCAmelCase : List[Any] = """My friends are cool but they eat too many carbs.""" _lowerCAmelCase : Union[str, Any] = tokenizer([ARTICLE_TO_SUMMARIZE] ,max_length=1024 ,return_tensors="""pt""" ).to(model.device ) _lowerCAmelCase : Any = model.generate( inputs["""input_ids"""] ,attention_mask=inputs["""attention_mask"""] ,num_beams=_lowerCamelCase ,max_length=_lowerCamelCase ,early_stopping=_lowerCamelCase ,decoder_start_token_id=model.config.decoder_start_token_id ,) torch.onnx.export( _lowerCamelCase ,( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) ,_lowerCamelCase ,opset_version=14 ,input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] ,output_names=["""output_ids"""] ,dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } ,example_outputs=_lowerCamelCase ,) logger.info("""Model exported to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : List[str] = remove_dup_initializers(os.path.abspath(_lowerCamelCase ) ) logger.info("""Deduplicated and optimized model written to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : str = onnxruntime.InferenceSession(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = ort_sess.run( _lowerCamelCase ,{ """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(_lowerCamelCase ), """max_length""": np.array(_lowerCamelCase ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } ,) np.testing.assert_allclose(summary_ids.cpu().numpy() ,ort_out[0] ,rtol=1e-3 ,atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def SCREAMING_SNAKE_CASE ( ) -> Any: _lowerCAmelCase : Any = parse_args() _lowerCAmelCase : List[Any] = 5 _lowerCAmelCase : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO ,) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _lowerCAmelCase : Optional[Any] = torch.device(args.device ) _lowerCAmelCase , _lowerCAmelCase : List[str] = load_model_tokenizer(args.model_name_or_path ,_lowerCamelCase ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(_lowerCamelCase ) if args.max_length: _lowerCAmelCase : Dict = args.max_length if args.num_beams: _lowerCAmelCase : Dict = args.num_beams if args.output_file_path: _lowerCAmelCase : Any = args.output_file_path else: _lowerCAmelCase : Union[str, Any] = """BART.onnx""" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if __name__ == "__main__": main()
44
1
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _a : Union[str, Any] = logging.get_logger(__name__) # General docstring _a : Any = 'RegNetConfig' # Base docstring _a : Tuple = 'facebook/regnet-y-040' _a : List[Any] = [1, 1_088, 7, 7] # Image classification docstring _a : Union[str, Any] = 'facebook/regnet-y-040' _a : Optional[Any] = 'tabby, tabby cat' _a : Union[str, Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ = 3 , a__ = 1 , a__ = 1 , a__ = "relu" , **a__ , ): super().__init__(**a__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _lowerCAmelCase : List[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _lowerCAmelCase : int = tf.keras.layers.ConvaD( filters=a__ , kernel_size=a__ , strides=a__ , padding="""VALID""" , groups=a__ , use_bias=a__ , name="""convolution""" , ) _lowerCAmelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) _lowerCAmelCase : List[str] = ACTaFN[activation] if activation is not None else tf.identity def __A ( self , a__ ): _lowerCAmelCase : List[str] = self.convolution(self.padding(a__ ) ) _lowerCAmelCase : Optional[Any] = self.normalization(a__ ) _lowerCAmelCase : Optional[int] = self.activation(a__ ) return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : str = config.num_channels _lowerCAmelCase : Optional[Any] = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="""embedder""" , ) def __A ( self , a__ ): _lowerCAmelCase : int = shape_list(a__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _lowerCAmelCase : Optional[int] = tf.transpose(a__ , perm=(0, 2, 3, 1) ) _lowerCAmelCase : List[Any] = self.embedder(a__ ) return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ = 2 , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : str = tf.keras.layers.ConvaD( filters=a__ , kernel_size=1 , strides=a__ , use_bias=a__ , name="""convolution""" ) _lowerCAmelCase : Optional[int] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) def __A ( self , a__ , a__ = False ): return self.normalization(self.convolution(a__ ) , training=a__ ) class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : List[Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=a__ , name="""pooler""" ) _lowerCAmelCase : int = [ tf.keras.layers.ConvaD(filters=a__ , kernel_size=1 , activation="""relu""" , name="""attention.0""" ), tf.keras.layers.ConvaD(filters=a__ , kernel_size=1 , activation="""sigmoid""" , name="""attention.2""" ), ] def __A ( self , a__ ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _lowerCAmelCase : int = self.pooler(a__ ) for layer_module in self.attention: _lowerCAmelCase : Dict = layer_module(a__ ) _lowerCAmelCase : Optional[Any] = hidden_state * pooled return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ , a__ , a__ = 1 , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : Any = in_channels != out_channels or stride != 1 _lowerCAmelCase : Tuple = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : str = ( TFRegNetShortCut(a__ , stride=a__ , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _lowerCAmelCase : str = [ TFRegNetConvLayer(a__ , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( a__ , stride=a__ , groups=a__ , activation=config.hidden_act , name="""layer.1""" ), TFRegNetConvLayer(a__ , kernel_size=1 , activation=a__ , name="""layer.2""" ), ] _lowerCAmelCase : Any = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : int = hidden_state for layer_module in self.layers: _lowerCAmelCase : List[str] = layer_module(a__ ) _lowerCAmelCase : Optional[Any] = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : Union[str, Any] = self.activation(a__ ) return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ , a__ , a__ = 1 , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : List[str] = in_channels != out_channels or stride != 1 _lowerCAmelCase : List[str] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : Tuple = ( TFRegNetShortCut(a__ , stride=a__ , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) _lowerCAmelCase : int = [ TFRegNetConvLayer(a__ , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( a__ , stride=a__ , groups=a__ , activation=config.hidden_act , name="""layer.1""" ), TFRegNetSELayer(a__ , reduced_channels=int(round(in_channels / 4 ) ) , name="""layer.2""" ), TFRegNetConvLayer(a__ , kernel_size=1 , activation=a__ , name="""layer.3""" ), ] _lowerCAmelCase : Dict = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : str = hidden_state for layer_module in self.layers: _lowerCAmelCase : Any = layer_module(a__ ) _lowerCAmelCase : List[str] = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : int = self.activation(a__ ) return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , a__ , a__ , a__ = 2 , a__ = 2 , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : Tuple = TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer _lowerCAmelCase : Any = [ # downsampling is done in the first layer with stride of 2 layer(a__ , a__ , a__ , stride=a__ , name="""layers.0""" ), *[layer(a__ , a__ , a__ , name=F"layers.{i+1}" ) for i in range(depth - 1 )], ] def __A ( self , a__ ): for layer_module in self.layers: _lowerCAmelCase : str = layer_module(a__ ) return hidden_state class __A ( tf.keras.layers.Layer ): def __init__( self , a__ , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : str = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( a__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="""stages.0""" , ) ) _lowerCAmelCase : Optional[Any] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(a__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(a__ , a__ , a__ , depth=a__ , name=F"stages.{i+1}" ) ) def __A ( self , a__ , a__ = False , a__ = True ): _lowerCAmelCase : Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _lowerCAmelCase : Any = hidden_states + (hidden_state,) _lowerCAmelCase : Optional[Any] = stage_module(a__ ) if output_hidden_states: _lowerCAmelCase : int = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=a__ , hidden_states=a__ ) @keras_serializable class __A ( tf.keras.layers.Layer ): _UpperCamelCase : Tuple = RegNetConfig def __init__( self , a__ , **a__ ): super().__init__(**a__ ) _lowerCAmelCase : Dict = config _lowerCAmelCase : List[Any] = TFRegNetEmbeddings(a__ , name="""embedder""" ) _lowerCAmelCase : str = TFRegNetEncoder(a__ , name="""encoder""" ) _lowerCAmelCase : Dict = tf.keras.layers.GlobalAveragePoolingaD(keepdims=a__ , name="""pooler""" ) @unpack_inputs def __A ( self , a__ , a__ = None , a__ = None , a__ = False , ): _lowerCAmelCase : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : List[str] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : Union[str, Any] = self.embedder(a__ , training=a__ ) _lowerCAmelCase : Any = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ , training=a__ ) _lowerCAmelCase : Union[str, Any] = encoder_outputs[0] _lowerCAmelCase : str = self.pooler(a__ ) # Change to NCHW output format have uniformity in the modules _lowerCAmelCase : Dict = tf.transpose(a__ , perm=(0, 3, 1, 2) ) _lowerCAmelCase : str = tf.transpose(a__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _lowerCAmelCase : List[str] = tuple([tf.transpose(a__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a__ , pooler_output=a__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = RegNetConfig _UpperCamelCase : List[str] = "regnet" _UpperCamelCase : Dict = "pixel_values" @property def __A ( self ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _a : List[str] = r'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' _a : List[str] = r'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , *a__ , **a__ ): super().__init__(a__ , *a__ , **a__ ) _lowerCAmelCase : int = TFRegNetMainLayer(a__ , name="""regnet""" ) @unpack_inputs @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self , a__ , a__ = None , a__ = None , a__=False , ): _lowerCAmelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : Optional[int] = self.regnet( pixel_values=a__ , output_hidden_states=a__ , return_dict=a__ , training=a__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , *a__ , **a__ ): super().__init__(a__ , *a__ , **a__ ) _lowerCAmelCase : Tuple = config.num_labels _lowerCAmelCase : List[str] = TFRegNetMainLayer(a__ , name="""regnet""" ) # classification head _lowerCAmelCase : Union[str, Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="""classifier.1""" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self , a__ = None , a__ = None , a__ = None , a__ = None , a__=False , ): _lowerCAmelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : str = self.regnet( a__ , output_hidden_states=a__ , return_dict=a__ , training=a__ ) _lowerCAmelCase : Optional[Any] = outputs.pooler_output if return_dict else outputs[1] _lowerCAmelCase : Any = self.classifier[0](a__ ) _lowerCAmelCase : Optional[int] = self.classifier[1](a__ ) _lowerCAmelCase : Optional[Any] = None if labels is None else self.hf_compute_loss(labels=a__ , logits=a__ ) if not return_dict: _lowerCAmelCase : Tuple = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states )
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ) -> List[Any]: # noqa: E741 _lowerCAmelCase : Optional[int] = len(_lowerCamelCase ) _lowerCAmelCase : str = 0 _lowerCAmelCase : Any = [0] * n _lowerCAmelCase : str = [False] * n _lowerCAmelCase : str = [False] * n def dfs(_lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ): if parent == root: out_edge_count += 1 _lowerCAmelCase : Any = True _lowerCAmelCase : int = at for to in l[at]: if to == parent: pass elif not visited[to]: _lowerCAmelCase : Union[str, Any] = dfs(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Optional[int] = min(low[at] ,low[to] ) # AP found via bridge if at < low[to]: _lowerCAmelCase : int = True # AP found via cycle if at == low[to]: _lowerCAmelCase : Tuple = True else: _lowerCAmelCase : Union[str, Any] = min(low[at] ,_lowerCamelCase ) return out_edge_count for i in range(_lowerCamelCase ): if not visited[i]: _lowerCAmelCase : int = 0 _lowerCAmelCase : Dict = dfs(_lowerCamelCase ,_lowerCamelCase ,-1 ,_lowerCamelCase ) _lowerCAmelCase : List[str] = out_edge_count > 1 for x in range(len(_lowerCamelCase ) ): if is_art[x] is True: print(_lowerCamelCase ) # Adjacency list of graph _a : Optional[Any] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
44
1
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar _a : Optional[Any] = TypeVar('T') class __A ( Generic[T] ): def __init__( self , a__ ): _lowerCAmelCase : Optional[Any] = data _lowerCAmelCase : Node[T] | None = None def __str__( self ): return F"{self.data}" class __A ( Generic[T] ): def __init__( self ): _lowerCAmelCase : Node[T] | None = None def __iter__( self ): _lowerCAmelCase : List[Any] = self.top while node: yield node.data _lowerCAmelCase : Dict = node.next def __str__( self ): return "->".join([str(a__ ) for item in self] ) def __len__( self ): return len(tuple(iter(self ) ) ) def __A ( self ): return self.top is None def __A ( self , a__ ): _lowerCAmelCase : str = Node(a__ ) if not self.is_empty(): _lowerCAmelCase : int = self.top _lowerCAmelCase : List[str] = node def __A ( self ): if self.is_empty(): raise IndexError("""pop from empty stack""" ) assert isinstance(self.top , a__ ) _lowerCAmelCase : Optional[Any] = self.top _lowerCAmelCase : Optional[Any] = self.top.next return pop_node.data def __A ( self ): if self.is_empty(): raise IndexError("""peek from empty stack""" ) assert self.top is not None return self.top.data def __A ( self ): _lowerCAmelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
44
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = XGLMTokenizer _UpperCamelCase : List[Any] = XGLMTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : Tuple = True def __A ( self ): super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[str] = """<pad>""" _lowerCAmelCase : List[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 __A ( self ): _lowerCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(a__ ) , 1008 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __A ( self ): _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Any = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def __A ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) _lowerCAmelCase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=a__ ) _lowerCAmelCase : List[str] = pickle.dumps(a__ ) pickle.loads(a__ ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = self.get_rust_tokenizer() _lowerCAmelCase : Tuple = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : List[Any] = tokenizer.tokenize(a__ ) _lowerCAmelCase : Tuple = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : str = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = self.get_rust_tokenizer() _lowerCAmelCase : Dict = tokenizer.encode(a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __A ( self ): _lowerCAmelCase : int = """Hello World!""" _lowerCAmelCase : Optional[int] = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Any = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _lowerCAmelCase : List[str] = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : List[str] = { """input_ids""": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/xglm-564M""" , padding=a__ , )
44
1
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): _a : str = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _a : str = 128_022 _a : Optional[Any] = 128_028 @require_sentencepiece class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = MaMaaaTokenizer _UpperCamelCase : int = False _UpperCamelCase : int = False _UpperCamelCase : int = True def __A ( self ): super().setUp() _lowerCAmelCase : Optional[Any] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] _lowerCAmelCase : Dict = dict(zip(a__ , range(len(a__ ) ) ) ) _lowerCAmelCase : List[Any] = Path(self.tmpdirname ) save_json(a__ , save_dir / VOCAB_FILES_NAMES["""vocab_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(a__ , save_dir / VOCAB_FILES_NAMES["""spm_file"""] ) _lowerCAmelCase : Any = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self , **a__ ): return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **a__ ) def __A ( self , a__ ): return ( "This is a test", "This is a test", ) def __A ( self ): _lowerCAmelCase : str = """</s>""" _lowerCAmelCase : Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __A ( self ): _lowerCAmelCase : Any = self.get_tokenizer() _lowerCAmelCase : Any = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<s>""" ) self.assertEqual(len(a__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip("""Skip this test while all models are still to be uploaded.""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase : Optional[int] = self.get_tokenizer() _lowerCAmelCase : Tuple = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [2, 3, 4, 5, 6] , ) _lowerCAmelCase : Union[str, Any] = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) _lowerCAmelCase : int = tokenizer.convert_tokens_to_string(a__ ) self.assertEqual(a__ , """This is a test""" ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : Optional[int] = {"""input_ids""": [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/m2m100_418M""" , revision="""c168bae485c864188cf9aa0e4108b0b6934dc91e""" , ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): _UpperCamelCase : Union[str, Any] = "facebook/m2m100_418M" _UpperCamelCase : Optional[Any] = [ "In my opinion, there are two levels of response from the French government.", "NSA Affair Emphasizes Complete Lack of Debate on Intelligence", ] _UpperCamelCase : Optional[int] = [ "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.", "L'affaire NSA souligne l'absence totale de débat sur le renseignement", ] # fmt: off _UpperCamelCase : List[str] = [EN_CODE, 593, 1_949, 115_781, 4, 71_586, 4_234, 60_633, 126_233, 432, 123_808, 15_592, 1_197, 117_132, 120_618, 5, 2] @classmethod def __A ( cls ): _lowerCAmelCase : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en""" , tgt_lang="""fr""" ) _lowerCAmelCase : Tuple = 1 return cls def __A ( self ): self.assertEqual(self.tokenizer.get_lang_id("""ar""" ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id("""en""" ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id("""ro""" ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id("""mr""" ) , 128063 ) def __A ( self ): _lowerCAmelCase : Tuple = self.tokenizer.get_vocab() self.assertEqual(len(a__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab["""<unk>"""] , 3 ) self.assertIn(self.tokenizer.get_lang_token("""en""" ) , a__ ) def __A ( self ): _lowerCAmelCase : List[str] = """en""" _lowerCAmelCase : int = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , a__ ) def __A ( self ): self.assertIn(a__ , self.tokenizer.all_special_ids ) # fmt: off _lowerCAmelCase : Union[str, Any] = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on _lowerCAmelCase : str = self.tokenizer.decode(a__ , skip_special_tokens=a__ ) _lowerCAmelCase : List[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=a__ ) self.assertEqual(a__ , a__ ) self.assertNotIn(self.tokenizer.eos_token , a__ ) def __A ( self ): _lowerCAmelCase : Dict = tempfile.mkdtemp() _lowerCAmelCase : Tuple = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(a__ ) _lowerCAmelCase : Tuple = MaMaaaTokenizer.from_pretrained(a__ ) self.assertDictEqual(new_tok.lang_token_to_id , a__ ) @require_torch def __A ( self ): _lowerCAmelCase : str = """en""" _lowerCAmelCase : int = """fr""" _lowerCAmelCase : Any = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=a__ , return_tensors="""pt""" ) _lowerCAmelCase : int = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: _lowerCAmelCase : Any = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def __A ( self ): _lowerCAmelCase : Union[str, Any] = """mr""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""mr""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) _lowerCAmelCase : List[Any] = """zh""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""zh""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def __A ( self ): _lowerCAmelCase : Union[str, Any] = """mr""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""mr""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) _lowerCAmelCase : Union[str, Any] = """zh""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("""zh""" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def __A ( self ): _lowerCAmelCase : Tuple = self.tokenizer._build_translation_inputs("""A test""" , return_tensors="""pt""" , src_lang="""en""" , tgt_lang="""ar""" ) self.assertEqual( nested_simplify(a__ ) , { # en_XX, A, test, EOS """input_ids""": [[128022, 58, 4183, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 128006, } , )
44
"""simple docstring""" from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : int ) -> List[str]: _lowerCAmelCase : Tuple = k_size // 2 _lowerCAmelCase , _lowerCAmelCase : List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] _lowerCAmelCase : Union[str, Any] = 1 / (2 * pi * sigma) * exp(-(square(_lowerCamelCase ) + square(_lowerCamelCase )) / (2 * square(_lowerCamelCase )) ) return g def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> Dict: _lowerCAmelCase , _lowerCAmelCase : str = image.shape[0], image.shape[1] # dst image height and width _lowerCAmelCase : Optional[int] = height - k_size + 1 _lowerCAmelCase : Dict = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows _lowerCAmelCase : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) _lowerCAmelCase : int = 0 for i, j in product(range(_lowerCamelCase ) ,range(_lowerCamelCase ) ): _lowerCAmelCase : Any = ravel(image[i : i + k_size, j : j + k_size] ) _lowerCAmelCase : Union[str, Any] = window row += 1 # turn the kernel into shape(k*k, 1) _lowerCAmelCase : List[Any] = gen_gaussian_kernel(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = ravel(_lowerCamelCase ) # reshape and get the dst image _lowerCAmelCase : int = dot(_lowerCamelCase ,_lowerCamelCase ).reshape(_lowerCamelCase ,_lowerCamelCase ).astype(_lowerCamelCase ) return dst if __name__ == "__main__": # read original image _a : Optional[Any] = imread(r'../image_data/lena.jpg') # turn image in gray scale value _a : Dict = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _a : Union[str, Any] = gaussian_filter(gray, 3, sigma=1) _a : List[Any] = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
44
1
"""simple docstring""" import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __A ( unittest.TestCase ): def __A ( self ): with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _lowerCAmelCase : Tuple = FlaxDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=a__ , cache_dir=a__ ) _lowerCAmelCase : Optional[int] = [t[-1] for t in os.walk(os.path.join(a__ , os.listdir(a__ )[0] , """snapshots""" ) )] _lowerCAmelCase : Tuple = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(""".bin""" ) for f in files ) @slow @require_flax class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=a__ ) _lowerCAmelCase : str = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : str = jax.random.PRNGKey(0 ) _lowerCAmelCase : Optional[int] = 4 _lowerCAmelCase : Any = jax.device_count() _lowerCAmelCase : Any = num_samples * [prompt] _lowerCAmelCase : List[str] = pipeline.prepare_inputs(a__ ) # shard inputs and rng _lowerCAmelCase : Optional[Any] = replicate(a__ ) _lowerCAmelCase : Optional[Any] = jax.random.split(a__ , a__ ) _lowerCAmelCase : str = shard(a__ ) _lowerCAmelCase : Any = pipeline(a__ , a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_5_1_4_7_4_5 ) < 1e-3 assert np.abs(np.abs(a__ , dtype=np.floataa ).sum() - 4_9_9_4_7.8_7_5 ) < 5e-1 _lowerCAmelCase : Dict = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(a__ ) == num_samples def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Dict = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""flax""" , safety_checker=a__ ) _lowerCAmelCase : Optional[int] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : Tuple = jax.random.PRNGKey(0 ) _lowerCAmelCase : Optional[int] = 50 _lowerCAmelCase : List[Any] = jax.device_count() _lowerCAmelCase : List[Any] = num_samples * [prompt] _lowerCAmelCase : Union[str, Any] = pipeline.prepare_inputs(a__ ) # shard inputs and rng _lowerCAmelCase : int = replicate(a__ ) _lowerCAmelCase : Dict = jax.random.split(a__ , a__ ) _lowerCAmelCase : Optional[int] = shard(a__ ) _lowerCAmelCase : Dict = pipeline(a__ , a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_5_6_5_2_4_0_1) ) < 1e-3 assert np.abs((np.abs(a__ , dtype=np.floataa ).sum() - 2_3_8_3_8_0_8.2) ) < 5e-1 def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Dict = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=a__ ) _lowerCAmelCase : Optional[Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : str = jax.random.PRNGKey(0 ) _lowerCAmelCase : List[Any] = 50 _lowerCAmelCase : int = jax.device_count() _lowerCAmelCase : Union[str, Any] = num_samples * [prompt] _lowerCAmelCase : Optional[Any] = pipeline.prepare_inputs(a__ ) # shard inputs and rng _lowerCAmelCase : Tuple = replicate(a__ ) _lowerCAmelCase : Any = jax.random.split(a__ , a__ ) _lowerCAmelCase : str = shard(a__ ) _lowerCAmelCase : str = pipeline(a__ , a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_4_0_0_3_9_0_6) ) < 1e-3 assert np.abs((np.abs(a__ , dtype=np.floataa ).sum() - 2_3_7_3_5_1_6.7_5) ) < 5e-1 def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : List[str] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa ) _lowerCAmelCase : List[Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : str = jax.random.PRNGKey(0 ) _lowerCAmelCase : Optional[int] = 50 _lowerCAmelCase : Dict = jax.device_count() _lowerCAmelCase : int = num_samples * [prompt] _lowerCAmelCase : List[str] = pipeline.prepare_inputs(a__ ) # shard inputs and rng _lowerCAmelCase : Union[str, Any] = replicate(a__ ) _lowerCAmelCase : List[Any] = jax.random.split(a__ , a__ ) _lowerCAmelCase : Optional[int] = shard(a__ ) _lowerCAmelCase : Optional[int] = pipeline(a__ , a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_4_0_0_3_9_0_6) ) < 1e-3 assert np.abs((np.abs(a__ , dtype=np.floataa ).sum() - 2_3_7_3_5_1_6.7_5) ) < 5e-1 def __A ( self ): _lowerCAmelCase : Any = FlaxDDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , set_alpha_to_one=a__ , steps_offset=1 , ) _lowerCAmelCase , _lowerCAmelCase : Optional[int] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , scheduler=a__ , safety_checker=a__ , ) _lowerCAmelCase : List[str] = scheduler.create_state() _lowerCAmelCase : List[Any] = scheduler_state _lowerCAmelCase : List[str] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : str = jax.random.PRNGKey(0 ) _lowerCAmelCase : List[Any] = 50 _lowerCAmelCase : str = jax.device_count() _lowerCAmelCase : Optional[int] = num_samples * [prompt] _lowerCAmelCase : str = pipeline.prepare_inputs(a__ ) # shard inputs and rng _lowerCAmelCase : Tuple = replicate(a__ ) _lowerCAmelCase : List[Any] = jax.random.split(a__ , a__ ) _lowerCAmelCase : Tuple = shard(a__ ) _lowerCAmelCase : Optional[Any] = pipeline(a__ , a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_4_5_0_4_3_9_4_5) ) < 1e-3 assert np.abs((np.abs(a__ , dtype=np.floataa ).sum() - 2_3_4_7_6_9_3.5) ) < 5e-1 def __A ( self ): _lowerCAmelCase : Tuple = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _lowerCAmelCase : Union[str, Any] = jax.device_count() _lowerCAmelCase : str = num_samples * [prompt] _lowerCAmelCase : Dict = jax.random.split(jax.random.PRNGKey(0 ) , a__ ) _lowerCAmelCase , _lowerCAmelCase : Any = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=a__ , ) _lowerCAmelCase : Union[str, Any] = replicate(a__ ) _lowerCAmelCase : List[Any] = pipeline.prepare_inputs(a__ ) _lowerCAmelCase : Dict = shard(a__ ) _lowerCAmelCase : List[str] = pipeline(a__ , a__ , a__ , jit=a__ ).images assert images.shape == (num_samples, 1, 512, 512, 3) _lowerCAmelCase : Dict = images[2, 0, 256, 10:17, 1] # With memory efficient attention _lowerCAmelCase , _lowerCAmelCase : Dict = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=a__ , use_memory_efficient_attention=a__ , ) _lowerCAmelCase : Any = replicate(a__ ) _lowerCAmelCase : Tuple = pipeline.prepare_inputs(a__ ) _lowerCAmelCase : List[str] = shard(a__ ) _lowerCAmelCase : List[Any] = pipeline(a__ , a__ , a__ , jit=a__ ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _lowerCAmelCase : List[str] = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
44
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : str = logging.get_logger(__name__) _a : int = { 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : str = "mra" def __init__( self , a__=50265 , a__=768 , a__=12 , a__=12 , a__=3072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=1 , a__=0.0_2 , a__=1e-5 , a__="absolute" , a__=4 , a__="full" , a__=0 , a__=0 , a__=1 , a__=0 , a__=2 , **a__ , ): super().__init__(pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__ ) _lowerCAmelCase : List[Any] = vocab_size _lowerCAmelCase : str = max_position_embeddings _lowerCAmelCase : Any = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Tuple = intermediate_size _lowerCAmelCase : List[Any] = hidden_act _lowerCAmelCase : Optional[Any] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = type_vocab_size _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = position_embedding_type _lowerCAmelCase : Dict = block_per_row _lowerCAmelCase : int = approx_mode _lowerCAmelCase : Dict = initial_prior_first_n_blocks _lowerCAmelCase : Any = initial_prior_diagonal_n_blocks
44
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
1
"""simple docstring""" from collections.abc import Sequence def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Sequence[float] ,_lowerCamelCase : float ) -> float: return sum(c * (x**i) for i, c in enumerate(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Sequence[float] ,_lowerCamelCase : float ) -> float: _lowerCAmelCase : Union[str, Any] = 0.0 for coeff in reversed(_lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = result * x + coeff return result if __name__ == "__main__": _a : Tuple = (0.0, 0.0, 5.0, 9.3, 7.0) _a : List[str] = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast 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 _a : Tuple = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[int] = ReformerTokenizer _UpperCamelCase : Tuple = ReformerTokenizerFast _UpperCamelCase : Tuple = True _UpperCamelCase : int = False _UpperCamelCase : Union[str, Any] = True def __A ( self ): super().setUp() _lowerCAmelCase : Any = ReformerTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : Optional[int] = """<s>""" _lowerCAmelCase : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __A ( self ): _lowerCAmelCase : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(a__ ) , 1000 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : Any = self.get_tokenizer() _lowerCAmelCase : Dict = self.get_rust_tokenizer() _lowerCAmelCase : Any = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : Any = tokenizer.tokenize(a__ ) _lowerCAmelCase : Dict = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() _lowerCAmelCase : str = tokenizer.encode(a__ ) _lowerCAmelCase : Dict = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) def __A ( self , a__=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): _lowerCAmelCase : Any = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) # Simple input _lowerCAmelCase : List[str] = """This is a simple input""" _lowerCAmelCase : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _lowerCAmelCase : List[Any] = ("""This is a simple input""", """This is a pair""") _lowerCAmelCase : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a__ , tokenizer_r.encode , a__ , max_length=a__ , padding="""max_length""" ) # Simple input self.assertRaises(a__ , tokenizer_r.encode_plus , a__ , max_length=a__ , padding="""max_length""" ) # Simple input self.assertRaises( a__ , tokenizer_r.batch_encode_plus , a__ , max_length=a__ , padding="""max_length""" , ) # Pair input self.assertRaises(a__ , tokenizer_r.encode , a__ , max_length=a__ , padding="""max_length""" ) # Pair input self.assertRaises(a__ , tokenizer_r.encode_plus , a__ , max_length=a__ , padding="""max_length""" ) # Pair input self.assertRaises( a__ , tokenizer_r.batch_encode_plus , a__ , max_length=a__ , padding="""max_length""" , ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase : Optional[Any] = ReformerTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Any = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [285, 46, 10, 170, 382] , ) _lowerCAmelCase : List[str] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : Tuple = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _lowerCAmelCase : List[str] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = """Hello World!""" _lowerCAmelCase : Tuple = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Dict = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) _lowerCAmelCase : Union[str, Any] = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @require_torch @slow def __A ( self ): import torch from transformers import ReformerConfig, ReformerModel # Build sequence _lowerCAmelCase : Union[str, Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] _lowerCAmelCase : Dict = """ """.join(a__ ) _lowerCAmelCase : List[str] = self.big_tokenizer.encode_plus(a__ , return_tensors="""pt""" ) _lowerCAmelCase : Optional[int] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) _lowerCAmelCase : List[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) _lowerCAmelCase : Optional[int] = encoded_sequence["""input_ids"""].shape _lowerCAmelCase : Any = ReformerModel(a__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**a__ ) model(**a__ ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : Dict = {"""input_ids""": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], """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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 _lowerCAmelCase : str = [ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=a__ , sequences=a__ , )
44
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
1
"""simple docstring""" import math import sys import cva import numpy as np def SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray ,_lowerCamelCase : float ) -> np.ndarray: # For applying gaussian function for each element in matrix. _lowerCAmelCase : Tuple = math.sqrt(_lowerCamelCase ) _lowerCAmelCase : Dict = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray ,_lowerCamelCase : int ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> np.ndarray: _lowerCAmelCase : List[Any] = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : float ) -> np.ndarray: # Creates a gaussian kernel of given dimension. _lowerCAmelCase : List[str] = np.zeros((kernel_size, kernel_size) ) for i in range(0 ,_lowerCamelCase ): for j in range(0 ,_lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase ,_lowerCamelCase ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray ,_lowerCamelCase : float ,_lowerCamelCase : float ,_lowerCamelCase : int ,) -> np.ndarray: _lowerCAmelCase : Union[str, Any] = np.zeros(img.shape ) _lowerCAmelCase : Dict = get_gauss_kernel(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase , _lowerCAmelCase : Tuple = img.shape for i in range(kernel_size // 2 ,size_x - kernel_size // 2 ): for j in range(kernel_size // 2 ,size_y - kernel_size // 2 ): _lowerCAmelCase : Union[str, Any] = get_slice(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : List[Any] = img_s - img_s[kernel_size // 2, kernel_size // 2] _lowerCAmelCase : List[Any] = vec_gaussian(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = np.multiply(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : int = np.multiply(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = val return imga def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list ) -> tuple: _lowerCAmelCase : List[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" _lowerCAmelCase : Optional[Any] = float(args[2] ) if args[2:] else 1.0 _lowerCAmelCase : Dict = float(args[3] ) if args[3:] else 1.0 if args[4:]: _lowerCAmelCase : List[str] = int(args[4] ) _lowerCAmelCase : List[str] = kernel_size + abs(kernel_size % 2 - 1 ) else: _lowerCAmelCase : Tuple = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": _a , _a , _a , _a : Optional[Any] = parse_args(sys.argv) _a : Optional[Any] = cva.imread(filename, 0) cva.imshow('input image', img) _a : List[str] = img / 255 _a : Union[str, Any] = out.astype('float32') _a : Dict = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) _a : Optional[int] = out * 255 _a : Union[str, Any] = np.uinta(out) cva.imshow('output image', out) cva.waitKey(0) cva.destroyAllWindows()
44
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
44
1
"""simple docstring""" import re from filelock import FileLock try: import nltk _a : int = True except (ImportError, ModuleNotFoundError): _a : Optional[Any] = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> str: re.sub("""<n>""" ,"""""" ,_lowerCamelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_lowerCamelCase ) )
44
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Dict = parent _lowerCAmelCase : str = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Dict = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Any = hidden_dropout_prob _lowerCAmelCase : List[str] = attention_probs_dropout_prob _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : Tuple = type_sequence_label_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Tuple = relative_attention _lowerCAmelCase : Tuple = position_biased_input _lowerCAmelCase : Dict = pos_att_type _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCAmelCase : str = None if self.use_token_type_ids: _lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return 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 , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self , a__ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] _lowerCAmelCase : List[Any] = model(a__ , token_type_ids=a__ )[0] _lowerCAmelCase : Any = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = DebertaVaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : int = self.num_labels _lowerCAmelCase : int = DebertaVaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = DebertaVaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = DebertaVaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _UpperCamelCase : str = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = True _UpperCamelCase : List[Any] = False _UpperCamelCase : List[Any] = False _UpperCamelCase : Dict = False _UpperCamelCase : Tuple = False def __A ( self ): _lowerCAmelCase : Optional[Any] = DebertaVaModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*a__ ) @slow def __A ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Tuple = DebertaVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def __A ( self ): pass @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) _lowerCAmelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _lowerCAmelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. _lowerCAmelCase : str = torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F"{output[:, 1:4, 1:4]}" )
44
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Optional[int] = logging.get_logger(__name__) _a : Tuple = { 'sail/poolformer_s12': 'https://huggingface.co/sail/poolformer_s12/resolve/main/config.json', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "poolformer" def __init__( self , a__=3 , a__=16 , a__=16 , a__=3 , a__=4.0 , a__=[2, 2, 6, 2] , a__=[64, 128, 320, 512] , a__=[7, 3, 3, 3] , a__=[4, 2, 2, 2] , a__=[2, 1, 1, 1] , a__=4 , a__=0.0 , a__="gelu" , a__=True , a__=1e-5 , a__=0.0_2 , **a__ , ): _lowerCAmelCase : List[Any] = num_channels _lowerCAmelCase : str = patch_size _lowerCAmelCase : Dict = stride _lowerCAmelCase : Optional[int] = padding _lowerCAmelCase : Optional[int] = pool_size _lowerCAmelCase : Dict = hidden_sizes _lowerCAmelCase : Optional[int] = mlp_ratio _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : Dict = patch_sizes _lowerCAmelCase : Tuple = strides _lowerCAmelCase : Any = num_encoder_blocks _lowerCAmelCase : Any = drop_path_rate _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : Optional[Any] = use_layer_scale _lowerCAmelCase : List[str] = layer_scale_init_value _lowerCAmelCase : List[Any] = initializer_range super().__init__(**a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = version.parse("1.11" ) @property def __A ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __A ( self ): return 2e-3
44
"""simple docstring""" import numpy as np import qiskit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 8 ,_lowerCamelCase : int | None = None ) -> str: _lowerCAmelCase : int = np.random.default_rng(seed=_lowerCamelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. _lowerCAmelCase : Dict = rng.integers(2 ,size=_lowerCamelCase ) # The set of states Alice will prepare. _lowerCAmelCase : Tuple = rng.integers(2 ,size=_lowerCamelCase ) # Measurement basis for Bob's qubits. _lowerCAmelCase : Union[str, Any] = rng.integers(2 ,size=_lowerCamelCase ) # Quantum Circuit to simulate BB84 _lowerCAmelCase : Dict = qiskit.QuantumCircuit(_lowerCamelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCamelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCAmelCase : int = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCAmelCase : List[str] = qiskit.execute(_lowerCamelCase ,_lowerCamelCase ,shots=1 ,seed_simulator=_lowerCamelCase ) # Returns the result of measurement. _lowerCAmelCase : List[Any] = job.result().get_counts(_lowerCamelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCAmelCase : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCAmelCase : List[Any] = gen_key[:key_len] if len(_lowerCamelCase ) >= key_len else gen_key.ljust(_lowerCamelCase ,"""0""" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
44
1
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets _a : str = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' _a : Union[str, Any] = '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n' _a : List[str] = '\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n "raw_values" : Returns a full set of errors in case of multioutput input.\n\n "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric("mse")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {\'mse\': 0.6123724356957945}\n\n If you\'re using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric("mse", "multilist")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mse\': array([0.41666667, 1. ])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def __A ( self ): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def __A ( self , a__ , a__ , a__=None , a__="uniform_average" , a__=True ): _lowerCAmelCase : int = mean_squared_error( a__ , a__ , sample_weight=a__ , multioutput=a__ , squared=a__ ) return {"mse": mse}
44
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _a : Union[str, Any] = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _a : List[str] = 10 _a : List[Any] = 256 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[MinHash]: if len(_lowerCamelCase ) < MIN_NUM_TOKENS: return None _lowerCAmelCase : Optional[Any] = MinHash(num_perm=_lowerCamelCase ) for token in set(_lowerCamelCase ): min_hash.update(token.encode() ) return min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> Set[str]: return {t for t in NON_ALPHA.split(_lowerCamelCase ) if len(t.strip() ) > 0} class __A : def __init__( self , *, a__ = 0.8_5 , ): _lowerCAmelCase : List[Any] = duplication_jaccard_threshold _lowerCAmelCase : Union[str, Any] = NUM_PERM _lowerCAmelCase : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase : Optional[int] = defaultdict(a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[Any] = self._index.query(a__ ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(a__ , a__ ) if len(a__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(a__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(a__ ) def __A ( self ): _lowerCAmelCase : int = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase : List[str] = [base] + list(a__ ) # reformat the cluster to be a list of dict _lowerCAmelCase : List[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(a__ ) return duplicate_clusters def __A ( self , a__ ): _lowerCAmelCase : Dict = self.get_duplicate_clusters() with open(a__ , """w""" ) as f: json.dump(a__ , a__ ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : Tuple = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ) -> Optional[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash ,ThreadedIterator(_lowerCamelCase ,max_queue_size=10000 ) ,chunksize=100 ,): if data is not None: yield data def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float ) -> List[str]: _lowerCAmelCase : Optional[Any] = DuplicationIndex(duplication_jaccard_threshold=_lowerCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_lowerCamelCase ) ) ,max_queue_size=100 ) ): di.add(_lowerCamelCase ,_lowerCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> float: _lowerCAmelCase : Any = get_tokens(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = get_tokens(_lowerCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _a : str = None def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : List[Any] ) -> Dict: _lowerCAmelCase : int = [] for elementa in cluster: _lowerCAmelCase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: _lowerCAmelCase : Any = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(_lowerCamelCase ,_lowerCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase : Any = 1 extremes.append(_lowerCamelCase ) return extremes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Any ) -> str: global _shared_dataset _lowerCAmelCase : Tuple = dataset _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Optional[Any] = partial(_find_cluster_extremes_shared ,jaccard_threshold=_lowerCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _lowerCamelCase ,_lowerCamelCase ,) ,total=len(_lowerCamelCase ) ,): extremes_list.append(_lowerCamelCase ) return extremes_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase : Tuple = make_duplicate_clusters(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase : Optional[int] = {} _lowerCAmelCase : Tuple = find_extremes(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : List[Any] = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase : List[Any] = dataset.filter(lambda _lowerCamelCase ,_lowerCamelCase : idx not in remove_indices ,with_indices=_lowerCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase : Tuple = element["""base_index"""] in extreme_dict if element["is_extreme"]: _lowerCAmelCase : Dict = extreme_dict[element["""base_index"""]]["""copies"""] print(f"Original dataset size: {len(_lowerCamelCase )}" ) print(f"Number of duplicate clusters: {len(_lowerCamelCase )}" ) print(f"Files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Filtered dataset size: {len(_lowerCamelCase )}" ) return ds_filter, duplicate_clusters
44
1
"""simple docstring""" from manim import * class __A ( SCREAMING_SNAKE_CASE_ ): def __A ( self ): _lowerCAmelCase : str = Rectangle(height=0.5 , width=0.5 ) _lowerCAmelCase : List[Any] = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) _lowerCAmelCase : Tuple = Rectangle(height=0.2_5 , width=0.2_5 ) _lowerCAmelCase : Optional[int] = [mem.copy() for i in range(6 )] _lowerCAmelCase : Optional[Any] = [mem.copy() for i in range(6 )] _lowerCAmelCase : List[str] = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : Dict = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : str = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : str = Text("""CPU""" , font_size=24 ) _lowerCAmelCase : str = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a__ ) _lowerCAmelCase : Union[str, Any] = [mem.copy() for i in range(4 )] _lowerCAmelCase : str = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : str = Text("""GPU""" , font_size=24 ) _lowerCAmelCase : str = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) gpu.move_to([-1, -1, 0] ) self.add(a__ ) _lowerCAmelCase : Optional[Any] = [mem.copy() for i in range(6 )] _lowerCAmelCase : Optional[Any] = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : int = Text("""Model""" , font_size=24 ) _lowerCAmelCase : int = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) model.move_to([3, -1.0, 0] ) self.add(a__ ) _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : str = [] for i, rect in enumerate(a__ ): _lowerCAmelCase : int = fill.copy().set_fill(a__ , opacity=0.8 ) target.move_to(a__ ) model_arr.append(a__ ) _lowerCAmelCase : Dict = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(a__ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(a__ ) self.add(*a__ , *a__ ) _lowerCAmelCase : str = [meta_mem.copy() for i in range(6 )] _lowerCAmelCase : Dict = [meta_mem.copy() for i in range(6 )] _lowerCAmelCase : Optional[int] = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : Optional[Any] = VGroup(*a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : int = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) _lowerCAmelCase : Dict = Text("""Disk""" , font_size=24 ) _lowerCAmelCase : Optional[int] = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) disk.move_to([-4, -1.2_5, 0] ) self.add(a__ , a__ ) _lowerCAmelCase : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _lowerCAmelCase : Dict = 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__ ) _lowerCAmelCase : List[str] = MarkupText( F"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(a__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(a__ ) _lowerCAmelCase : List[str] = MarkupText( F"Now watch as an input is passed through the model\nand how the memory is utilized and handled." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(a__ ) ) _lowerCAmelCase : Union[str, Any] = Square(0.3 ) input.set_fill(a__ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , a__ , buff=0.5 ) self.play(Write(a__ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=a__ , buff=0.0_2 ) self.play(MoveToTarget(a__ ) ) self.play(FadeOut(a__ ) ) _lowerCAmelCase : Dict = Arrow(start=a__ , end=a__ , color=a__ , buff=0.5 ) a.next_to(model_arr[0].get_left() , a__ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) _lowerCAmelCase : Optional[Any] = MarkupText( F"As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(a__ , run_time=3 ) ) _lowerCAmelCase : Optional[int] = {"""run_time""": 1, """fade_in""": True, """fade_out""": True, """buff""": 0.0_2} self.play( Write(a__ ) , Circumscribe(model_arr[0] , color=a__ , **a__ ) , Circumscribe(model_cpu_arr[0] , color=a__ , **a__ ) , Circumscribe(gpu_rect[0] , color=a__ , **a__ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) _lowerCAmelCase : Any = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.0_2 , a__ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.0_2 ) _lowerCAmelCase : Union[str, Any] = AnimationGroup( FadeOut(a__ , run_time=0.5 ) , MoveToTarget(a__ , run_time=0.5 ) , FadeIn(a__ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(a__ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: _lowerCAmelCase : int = 0.7 self.play( Circumscribe(model_arr[i] , **a__ ) , Circumscribe(cpu_left_col_base[i] , **a__ ) , Circumscribe(cpu_left_col_base[i + 1] , color=a__ , **a__ ) , Circumscribe(gpu_rect[0] , color=a__ , **a__ ) , Circumscribe(model_arr[i + 1] , color=a__ , **a__ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.0_2 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=a__ , **a__ ) , Circumscribe(cpu_left_col_base[-1] , color=a__ , **a__ ) , Circumscribe(gpu_rect[0] , color=a__ , **a__ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) _lowerCAmelCase : Any = a_c _lowerCAmelCase : Any = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.0_2 , buff=0.5 ) self.play( FadeOut(a__ ) , FadeOut(a__ , run_time=0.5 ) , ) _lowerCAmelCase : List[str] = MarkupText(F"Inference on a model too large for GPU memory\nis successfully completed." , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(a__ , run_time=3 ) , MoveToTarget(a__ ) ) self.wait()
44
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
1
"""simple docstring""" from typing import List, Optional, Union import torch 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, ) _a : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[int] ,_lowerCamelCase : Any=8 ) -> int: _lowerCAmelCase : Union[str, Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _lowerCAmelCase : Optional[Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ , a__ , ): super().__init__() self.register_modules( unet=a__ , scheduler=a__ , movq=a__ , ) _lowerCAmelCase : int = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): if latents is None: _lowerCAmelCase : Dict = randn_tensor(a__ , generator=a__ , device=a__ , dtype=a__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) _lowerCAmelCase : Optional[Any] = latents.to(a__ ) _lowerCAmelCase : List[str] = latents * scheduler.init_noise_sigma return latents def __A ( self , a__=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _lowerCAmelCase : Tuple = torch.device(F"cuda:{gpu_id}" ) _lowerCAmelCase : Optional[Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(a__ , a__ ) def __A ( self , a__=0 ): 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.""" ) _lowerCAmelCase : List[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) _lowerCAmelCase : Optional[int] = None for cpu_offloaded_model in [self.unet, self.movq]: _lowerCAmelCase , _lowerCAmelCase : List[str] = cpu_offload_with_hook(a__ , a__ , prev_module_hook=a__ ) # We'll offload the last model manually. _lowerCAmelCase : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __A ( self ): 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 , a__ , a__ , a__ , a__ = 512 , a__ = 512 , a__ = 100 , a__ = 4.0 , a__ = 1 , a__ = None , a__ = None , a__ = "pil" , a__ = True , ): _lowerCAmelCase : Optional[Any] = self._execution_device _lowerCAmelCase : Dict = guidance_scale > 1.0 if isinstance(a__ , a__ ): _lowerCAmelCase : List[str] = torch.cat(a__ , dim=0 ) if isinstance(a__ , a__ ): _lowerCAmelCase : Union[str, Any] = torch.cat(a__ , dim=0 ) if isinstance(a__ , a__ ): _lowerCAmelCase : str = torch.cat(a__ , dim=0 ) _lowerCAmelCase : Optional[Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: _lowerCAmelCase : Optional[int] = image_embeds.repeat_interleave(a__ , dim=0 ) _lowerCAmelCase : List[Any] = negative_image_embeds.repeat_interleave(a__ , dim=0 ) _lowerCAmelCase : Optional[int] = hint.repeat_interleave(a__ , dim=0 ) _lowerCAmelCase : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=a__ ) _lowerCAmelCase : str = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=a__ ) self.scheduler.set_timesteps(a__ , device=a__ ) _lowerCAmelCase : Any = self.scheduler.timesteps _lowerCAmelCase : List[str] = self.movq.config.latent_channels _lowerCAmelCase , _lowerCAmelCase : Any = downscale_height_and_width(a__ , a__ , self.movq_scale_factor ) # create initial latent _lowerCAmelCase : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , a__ , a__ , a__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(a__ ) ): # expand the latents if we are doing classifier free guidance _lowerCAmelCase : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _lowerCAmelCase : Any = {"""image_embeds""": image_embeds, """hint""": hint} _lowerCAmelCase : Optional[int] = self.unet( sample=a__ , timestep=a__ , encoder_hidden_states=a__ , added_cond_kwargs=a__ , return_dict=a__ , )[0] if do_classifier_free_guidance: _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) _lowerCAmelCase , _lowerCAmelCase : Any = noise_pred.chunk(2 ) _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = variance_pred.chunk(2 ) _lowerCAmelCase : int = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _lowerCAmelCase : 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"] ): _lowerCAmelCase , _lowerCAmelCase : List[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _lowerCAmelCase : List[str] = self.scheduler.step( a__ , a__ , a__ , generator=a__ , )[0] # post-processing _lowerCAmelCase : Optional[int] = 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"]: _lowerCAmelCase : List[str] = image * 0.5 + 0.5 _lowerCAmelCase : Tuple = image.clamp(0 , 1 ) _lowerCAmelCase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(a__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a__ )
44
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "bert-generation" def __init__( self , a__=50358 , a__=1024 , a__=24 , a__=16 , a__=4096 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=0.0_2 , a__=1e-12 , a__=0 , a__=2 , a__=1 , a__="absolute" , a__=True , **a__ , ): super().__init__(pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__ ) _lowerCAmelCase : List[str] = vocab_size _lowerCAmelCase : Dict = hidden_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : Optional[int] = intermediate_size _lowerCAmelCase : str = hidden_dropout_prob _lowerCAmelCase : Optional[int] = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = max_position_embeddings _lowerCAmelCase : Union[str, Any] = initializer_range _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : Optional[Any] = position_embedding_type _lowerCAmelCase : Optional[Any] = use_cache
44
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : List[Any] = torch.exp(_lowerCamelCase ) _lowerCAmelCase : List[Any] = torch.sum(_lowerCamelCase ,dim=1 ) # sum of exp(x_i) _lowerCAmelCase : Dict = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : int = config.output_attentions _lowerCAmelCase : Any = config.output_hidden_states _lowerCAmelCase : List[Any] = nn.ModuleList([BertLayer(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : Any = nn.ModuleList([BertHighway(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : str = [-1 for _ in range(config.num_hidden_layers )] def __A ( self , a__ ): if (type(a__ ) is float) or (type(a__ ) is int): for i in range(len(self.early_exit_entropy ) ): _lowerCAmelCase : Tuple = x else: _lowerCAmelCase : Optional[int] = x def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __A ( self , a__ , a__=None , a__=None , a__=None , a__=None , ): _lowerCAmelCase : Any = () _lowerCAmelCase : Optional[int] = () _lowerCAmelCase : List[Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _lowerCAmelCase : str = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[str] = layer_module( a__ , a__ , head_mask[i] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = layer_outputs[0] if self.output_attentions: _lowerCAmelCase : Dict = all_attentions + (layer_outputs[1],) _lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Optional[int] = current_outputs + (all_attentions,) _lowerCAmelCase : Optional[Any] = self.highway[i](a__ ) # logits, pooled_output if not self.training: _lowerCAmelCase : Tuple = highway_exit[0] _lowerCAmelCase : Any = entropy(a__ ) _lowerCAmelCase : Optional[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _lowerCAmelCase : Union[str, Any] = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _lowerCAmelCase : List[str] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a__ , i + 1 ) else: _lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _lowerCAmelCase : List[Any] = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[Any] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : List[str] = outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Any = outputs + (all_attentions,) _lowerCAmelCase : Optional[int] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config _lowerCAmelCase : Tuple = BertEmbeddings(a__ ) _lowerCAmelCase : Tuple = DeeBertEncoder(a__ ) _lowerCAmelCase : List[str] = BertPooler(a__ ) self.init_weights() def __A ( self ): self.encoder.init_highway_pooler(self.pooler ) def __A ( self ): return self.embeddings.word_embeddings def __A ( self , a__ ): _lowerCAmelCase : Dict = value def __A ( self , a__ ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a__ ) @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _lowerCAmelCase : Any = input_ids.size() elif inputs_embeds is not None: _lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _lowerCAmelCase : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _lowerCAmelCase : List[Any] = torch.ones(a__ , device=a__ ) if encoder_attention_mask is None: _lowerCAmelCase : Optional[Any] = torch.ones(a__ , device=a__ ) if token_type_ids is None: _lowerCAmelCase : Dict = torch.zeros(a__ , dtype=torch.long , device=a__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(a__ , a__ , a__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _lowerCAmelCase : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _lowerCAmelCase : Tuple = encoder_attention_mask[:, None, None, :] _lowerCAmelCase : Union[str, Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _lowerCAmelCase : Optional[Any] = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _lowerCAmelCase : Optional[int] = self.get_head_mask(a__ , self.config.num_hidden_layers ) _lowerCAmelCase : Dict = self.embeddings( input_ids=a__ , position_ids=a__ , token_type_ids=a__ , inputs_embeds=a__ ) _lowerCAmelCase : Union[str, Any] = self.encoder( a__ , attention_mask=a__ , head_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Dict = encoder_outputs[0] _lowerCAmelCase : Union[str, Any] = self.pooler(a__ ) _lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ ): _lowerCAmelCase : str = message _lowerCAmelCase : str = exit_layer # start from 1! class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Any = BertPooler(a__ ) _lowerCAmelCase : str = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def __A ( self , a__ ): # Pooler _lowerCAmelCase : Tuple = encoder_outputs[0] _lowerCAmelCase : int = self.pooler(a__ ) # "return" pooler_output # BertModel _lowerCAmelCase : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _lowerCAmelCase : Optional[int] = bmodel_output[1] _lowerCAmelCase : Tuple = self.dropout(a__ ) _lowerCAmelCase : Dict = self.classifier(a__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[str] = config.num_labels _lowerCAmelCase : Optional[Any] = config.num_hidden_layers _lowerCAmelCase : str = DeeBertModel(a__ ) _lowerCAmelCase : Tuple = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : List[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=-1 , a__=False , ): _lowerCAmelCase : Dict = self.num_layers try: _lowerCAmelCase : str = self.bert( a__ , attention_mask=a__ , token_type_ids=a__ , position_ids=a__ , head_mask=a__ , inputs_embeds=a__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _lowerCAmelCase : Any = outputs[1] _lowerCAmelCase : Optional[int] = self.dropout(a__ ) _lowerCAmelCase : List[str] = self.classifier(a__ ) _lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : int = e.exit_layer _lowerCAmelCase : Union[str, Any] = outputs[0] if not self.training: _lowerCAmelCase : Tuple = entropy(a__ ) _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Tuple = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase : Optional[Any] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Dict = highway_exit[0] if not self.training: highway_logits_all.append(a__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Optional[int] = CrossEntropyLoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(a__ ) if train_highway: _lowerCAmelCase : List[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Dict = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Dict = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
1
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __A ( unittest.TestCase ): _UpperCamelCase : str = JukeboxTokenizer _UpperCamelCase : Optional[int] = { "artist": "Zac Brown Band", "genres": "Country", "lyrics": "I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ", } @require_torch def __A ( self ): import torch _lowerCAmelCase : Tuple = JukeboxTokenizer.from_pretrained("""openai/jukebox-1b-lyrics""" ) _lowerCAmelCase : Optional[Any] = tokenizer(**self.metas )["""input_ids"""] # fmt: off _lowerCAmelCase : int = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __A ( self ): import torch _lowerCAmelCase : Optional[int] = JukeboxTokenizer.from_pretrained("""openai/jukebox-5b-lyrics""" ) _lowerCAmelCase : Any = tokenizer(**self.metas )["""input_ids"""] # fmt: off _lowerCAmelCase : int = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
44
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : str = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , a__ = None , a__ = None , **a__ , ): super().__init__(self , **a__ ) _lowerCAmelCase : Any = repo_info _lowerCAmelCase : Optional[Any] = token _lowerCAmelCase : Optional[int] = None def __A ( self ): if self.dir_cache is None: _lowerCAmelCase : Optional[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowerCAmelCase : 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 __A ( self , a__ , a__ = "rb" , **a__ , ): if not isinstance(self.repo_info , a__ ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) _lowerCAmelCase : Tuple = 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 __A ( self , a__ , **a__ ): self._get_dirs() _lowerCAmelCase : Union[str, Any] = self._strip_protocol(a__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a__ ) def __A ( self , a__ , a__=False , **a__ ): self._get_dirs() _lowerCAmelCase : Any = PurePosixPath(path.strip("""/""" ) ) _lowerCAmelCase : List[str] = {} for p, f in self.dir_cache.items(): _lowerCAmelCase : Any = PurePosixPath(p.strip("""/""" ) ) _lowerCAmelCase : Optional[int] = p.parent if root == path: _lowerCAmelCase : Dict = f _lowerCAmelCase : Union[str, Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
44
1
"""simple docstring""" from collections import Counter from timeit import timeit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str = "" ,) -> bool: return sum(c % 2 for c in Counter(input_str.replace(""" """ ,"""""" ).lower() ).values() ) < 2 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str = "" ) -> bool: if len(_lowerCamelCase ) == 0: return True _lowerCAmelCase : Union[str, Any] = input_str.replace(""" """ ,"""""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string _lowerCAmelCase : dict[str, int] = {} for character in lower_case_input_str: _lowerCAmelCase : Optional[Any] = character_freq_dict.get(_lowerCamelCase ,0 ) + 1 _lowerCAmelCase : Optional[int] = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str = "" ) -> None: print("""\nFor string = """ ,_lowerCamelCase ,""":""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" ,"""\tans =""" ,can_string_be_rearranged_as_palindrome_counter(_lowerCamelCase ) ,"""\ttime =""" ,timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" ,setup="""import __main__ as z""" ,) ,"""seconds""" ,) print( """> can_string_be_rearranged_as_palindrome()""" ,"""\tans =""" ,can_string_be_rearranged_as_palindrome(_lowerCamelCase ) ,"""\ttime =""" ,timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" ,setup="""import __main__ as z""" ,) ,"""seconds""" ,) if __name__ == "__main__": _a : Tuple = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) _a : Dict = can_string_be_rearranged_as_palindrome_counter(check_str) print(F"""{check_str} can {"" if status else "not "}be rearranged as a palindrome""")
44
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_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""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): 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 __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
1
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() _a : str = logging.get_logger(__name__) _a : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn.grep_linear': 'encoder.layers.*.attention.gru_rel_pos_linear', 'self_attn.relative_attention_bias': 'encoder.layers.*.attention.rel_attn_embed', 'self_attn.grep_a': 'encoder.layers.*.attention.gru_rel_pos_const', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'ctc_proj', 'mask_emb': 'masked_spec_embed', } _a : List[Any] = [ 'ctc_proj', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ,_lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[int] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ) -> List[str]: for attribute in key.split(""".""" ): _lowerCAmelCase : Tuple = getattr(_lowerCamelCase ,_lowerCamelCase ) if weight_type is not None: _lowerCAmelCase : int = getattr(_lowerCamelCase ,_lowerCamelCase ).shape else: _lowerCAmelCase : str = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": _lowerCAmelCase : Optional[Any] = value elif weight_type == "weight_g": _lowerCAmelCase : str = value elif weight_type == "weight_v": _lowerCAmelCase : Union[str, Any] = value elif weight_type == "bias": _lowerCAmelCase : Optional[int] = value else: _lowerCAmelCase : List[Any] = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : Dict ) -> Any: _lowerCAmelCase : int = [] _lowerCAmelCase : Dict = fairseq_model.state_dict() _lowerCAmelCase : int = hf_model.feature_extractor for name, value in fairseq_dict.items(): _lowerCAmelCase : int = False if "conv_layers" in name: load_conv_layer( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,hf_model.config.feat_extract_norm == """group""" ,) _lowerCAmelCase : Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _lowerCAmelCase : List[Any] = True if "*" in mapped_key: _lowerCAmelCase : int = name.split(_lowerCamelCase )[0].split(""".""" )[-2] _lowerCAmelCase : Any = mapped_key.replace("""*""" ,_lowerCamelCase ) if "weight_g" in name: _lowerCAmelCase : int = """weight_g""" elif "weight_v" in name: _lowerCAmelCase : List[str] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: _lowerCAmelCase : Tuple = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj _lowerCAmelCase : str = """weight""" else: _lowerCAmelCase : Dict = None set_recursively(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) continue if not is_used: unused_weights.append(_lowerCamelCase ) logger.warning(f"Unused weights: {unused_weights}" ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Any ,_lowerCamelCase : Tuple ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Optional[Any] ) -> List[str]: _lowerCAmelCase : List[Any] = full_name.split("""conv_layers.""" )[-1] _lowerCAmelCase : Optional[Any] = name.split(""".""" ) _lowerCAmelCase : Dict = int(items[0] ) _lowerCAmelCase : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _lowerCAmelCase : List[str] = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _lowerCAmelCase : Any = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _lowerCAmelCase : List[str] = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _lowerCAmelCase : int = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_lowerCamelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : List[Any] ,_lowerCamelCase : str=None ) -> Dict: # load the pre-trained checkpoints _lowerCAmelCase : int = torch.load(_lowerCamelCase ) _lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint["""cfg"""] ) _lowerCAmelCase : Tuple = WavLMOrig(_lowerCamelCase ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: _lowerCAmelCase : Any = WavLMConfig.from_pretrained(_lowerCamelCase ) else: _lowerCAmelCase : Any = WavLMConfig() _lowerCAmelCase : Union[str, Any] = WavLMModel(_lowerCamelCase ) recursively_load_weights(_lowerCamelCase ,_lowerCamelCase ) hf_wavlm.save_pretrained(_lowerCamelCase ) if __name__ == "__main__": _a : Optional[int] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') _a : int = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
44
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
1
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class __A : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=False , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : List[str] = parent _lowerCAmelCase : Optional[int] = batch_size _lowerCAmelCase : str = seq_length _lowerCAmelCase : List[Any] = is_training _lowerCAmelCase : Union[str, Any] = use_input_mask _lowerCAmelCase : List[str] = use_token_type_ids _lowerCAmelCase : Tuple = use_labels _lowerCAmelCase : List[Any] = vocab_size _lowerCAmelCase : Union[str, Any] = hidden_size _lowerCAmelCase : Union[str, Any] = num_hidden_layers _lowerCAmelCase : Any = num_attention_heads _lowerCAmelCase : str = intermediate_size _lowerCAmelCase : Dict = hidden_act _lowerCAmelCase : List[Any] = hidden_dropout_prob _lowerCAmelCase : int = attention_probs_dropout_prob _lowerCAmelCase : Dict = max_position_embeddings _lowerCAmelCase : List[Any] = type_vocab_size _lowerCAmelCase : int = type_sequence_label_size _lowerCAmelCase : Union[str, Any] = initializer_range _lowerCAmelCase : List[str] = num_labels _lowerCAmelCase : Optional[int] = num_choices _lowerCAmelCase : Optional[Any] = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[int] = None if self.use_input_mask: _lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase : List[str] = None if self.use_token_type_ids: _lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : int = None _lowerCAmelCase : Any = None _lowerCAmelCase : Optional[Any] = None if self.use_labels: _lowerCAmelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a__ , initializer_range=self.initializer_range , ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = LlamaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = model(a__ , attention_mask=a__ ) _lowerCAmelCase : str = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Tuple = True _lowerCAmelCase : Tuple = LlamaModel(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Optional[Any] = model( a__ , attention_mask=a__ , encoder_hidden_states=a__ , ) _lowerCAmelCase : Any = model(a__ , attention_mask=a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Tuple = LlamaForCausalLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : int = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Optional[int] = True _lowerCAmelCase : Optional[int] = True _lowerCAmelCase : Tuple = LlamaForCausalLM(config=a__ ) model.to(a__ ) model.eval() # first forward pass _lowerCAmelCase : Union[str, Any] = model( a__ , attention_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , use_cache=a__ , ) _lowerCAmelCase : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCAmelCase : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _lowerCAmelCase : Any = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _lowerCAmelCase : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) _lowerCAmelCase : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) _lowerCAmelCase : Tuple = model( a__ , attention_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , output_hidden_states=a__ , )["""hidden_states"""][0] _lowerCAmelCase : Optional[Any] = model( a__ , attention_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , past_key_values=a__ , output_hidden_states=a__ , )["""hidden_states"""][0] # select random slice _lowerCAmelCase : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() _lowerCAmelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCAmelCase : Optional[int] = 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 __A ( self ): _lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : int = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _UpperCamelCase : Dict = (LlamaForCausalLM,) if is_torch_available() else () _UpperCamelCase : Union[str, Any] = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = False _UpperCamelCase : Dict = False def __A ( self ): _lowerCAmelCase : Dict = LlamaModelTester(self ) _lowerCAmelCase : List[str] = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _lowerCAmelCase : List[str] = type self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : Optional[int] = 3 _lowerCAmelCase : Union[str, Any] = input_dict["""input_ids"""] _lowerCAmelCase : str = input_ids.ne(1 ).to(a__ ) _lowerCAmelCase : int = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _lowerCAmelCase : List[Any] = LlamaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : int = model(a__ , attention_mask=a__ , labels=a__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : int = 3 _lowerCAmelCase : str = """single_label_classification""" _lowerCAmelCase : Optional[int] = input_dict["""input_ids"""] _lowerCAmelCase : Union[str, Any] = input_ids.ne(1 ).to(a__ ) _lowerCAmelCase : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _lowerCAmelCase : Union[str, Any] = LlamaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , labels=a__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : List[str] = 3 _lowerCAmelCase : int = """multi_label_classification""" _lowerCAmelCase : Tuple = input_dict["""input_ids"""] _lowerCAmelCase : Dict = input_ids.ne(1 ).to(a__ ) _lowerCAmelCase : int = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _lowerCAmelCase : Union[str, Any] = LlamaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : int = model(a__ , attention_mask=a__ , labels=a__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def __A ( self ): pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def __A ( self , a__ ): _lowerCAmelCase , _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : int = ids_tensor([1, 10] , config.vocab_size ) _lowerCAmelCase : int = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _lowerCAmelCase : List[str] = LlamaModel(a__ ) original_model.to(a__ ) original_model.eval() _lowerCAmelCase : List[str] = original_model(a__ ).last_hidden_state _lowerCAmelCase : Optional[Any] = original_model(a__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _lowerCAmelCase : Tuple = {"""type""": scaling_type, """factor""": 1_0.0} _lowerCAmelCase : Optional[Any] = LlamaModel(a__ ) scaled_model.to(a__ ) scaled_model.eval() _lowerCAmelCase : Any = scaled_model(a__ ).last_hidden_state _lowerCAmelCase : Optional[Any] = scaled_model(a__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a__ , a__ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(a__ , a__ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(a__ , a__ , atol=1e-5 ) ) @require_torch class __A ( unittest.TestCase ): @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ): _lowerCAmelCase : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] _lowerCAmelCase : List[Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" , device_map="""auto""" ) _lowerCAmelCase : Tuple = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 _lowerCAmelCase : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , a__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCAmelCase : List[str] = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , a__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = [1, 306, 4658, 278, 6593, 310, 2834, 338] _lowerCAmelCase : List[Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" , device_map="""auto""" ) _lowerCAmelCase : Tuple = model(torch.tensor(a__ ) ) # Expected mean on dim = -1 _lowerCAmelCase : Union[str, Any] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , a__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCAmelCase : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , a__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ): _lowerCAmelCase : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] _lowerCAmelCase : Dict = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" , device_map="""auto""" ) _lowerCAmelCase : Tuple = model(torch.tensor(a__ ) ) # Expected mean on dim = -1 _lowerCAmelCase : Optional[Any] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , a__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCAmelCase : List[str] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , a__ , atol=1e-2 , rtol=1e-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def __A ( self ): _lowerCAmelCase : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] _lowerCAmelCase : Optional[Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" , device_map="""auto""" ) _lowerCAmelCase : str = model(torch.tensor(a__ ) ) _lowerCAmelCase : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , a__ , atol=1e-2 , rtol=1e-2 ) # fmt: off _lowerCAmelCase : Union[str, Any] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , a__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip("""Model is curently gated""" ) @slow def __A ( self ): _lowerCAmelCase : List[str] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" _lowerCAmelCase : str = """Simply put, the theory of relativity states that """ _lowerCAmelCase : List[str] = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) _lowerCAmelCase : Optional[Any] = tokenizer.encode(a__ , return_tensors="""pt""" ) _lowerCAmelCase : Optional[Any] = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" , device_map="""sequential""" , use_safetensors=a__ ) # greedy generation outputs _lowerCAmelCase : Optional[int] = model.generate(a__ , max_new_tokens=64 , top_p=a__ , temperature=1 , do_sample=a__ ) _lowerCAmelCase : Dict = tokenizer.decode(generated_ids[0] , skip_special_tokens=a__ ) self.assertEqual(a__ , a__ )
44
"""simple docstring""" _a : List[str] = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.13.2', 'requests-mock': 'requests-mock==1.10.0', 'importlib_metadata': 'importlib_metadata', 'invisible-watermark': 'invisible-watermark', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2', 'jaxlib': 'jaxlib>=0.1.65', 'Jinja2': 'Jinja2', 'k-diffusion': 'k-diffusion>=0.0.12', 'torchsde': 'torchsde', 'note_seq': 'note_seq', 'librosa': 'librosa', 'numpy': 'numpy', 'omegaconf': 'omegaconf', 'parameterized': 'parameterized', 'protobuf': 'protobuf>=3.20.3,<4', 'pytest': 'pytest', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'ruff': 'ruff>=0.0.241', 'safetensors': 'safetensors', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'scipy': 'scipy', 'onnx': 'onnx', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'tensorboard': 'tensorboard', 'torch': 'torch>=1.4', 'torchvision': 'torchvision', 'transformers': 'transformers>=4.25.1', 'urllib3': 'urllib3<=2.0.0', }
44
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _a : Union[str, Any] = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class __A ( unittest.TestCase ): _UpperCamelCase : int = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _UpperCamelCase : List[str] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _UpperCamelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _UpperCamelCase : Optional[int] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __A ( self ): _lowerCAmelCase : Tuple = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) _lowerCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}] ) _lowerCAmelCase : List[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}] ) _lowerCAmelCase : Any = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(a__ ) , [ [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}], [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}], ] , ) _lowerCAmelCase : Optional[int] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}] ) # Legacy behavior _lowerCAmelCase : Tuple = text_classifier("""This is great !""" , return_all_scores=a__ ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}] ) _lowerCAmelCase : int = text_classifier("""This is great !""" , return_all_scores=a__ ) self.assertEqual( nested_simplify(a__ ) , [[{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}]] ) _lowerCAmelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=a__ ) self.assertEqual( nested_simplify(a__ ) , [ [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}], [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}], ] , ) _lowerCAmelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=a__ ) self.assertEqual( nested_simplify(a__ ) , [ {"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_0""", """score""": 0.5_0_4}, ] , ) @require_torch def __A ( self ): import torch _lowerCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) _lowerCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}] ) @require_tf def __A ( self ): _lowerCAmelCase : Union[str, Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) _lowerCAmelCase : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """LABEL_0""", """score""": 0.5_0_4}] ) @slow @require_torch def __A ( self ): _lowerCAmelCase : Union[str, Any] = pipeline("""text-classification""" ) _lowerCAmelCase : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) _lowerCAmelCase : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) _lowerCAmelCase : int = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """POSITIVE""", """score""": 0.9_8_8}] ) @slow @require_tf def __A ( self ): _lowerCAmelCase : Tuple = pipeline("""text-classification""" , framework="""tf""" ) _lowerCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) _lowerCAmelCase : int = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) _lowerCAmelCase : Optional[Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": """POSITIVE""", """score""": 0.9_8_8}] ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = TextClassificationPipeline(model=a__ , tokenizer=a__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def __A ( self , a__ , a__ ): _lowerCAmelCase : Dict = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 _lowerCAmelCase : Any = """HuggingFace is in""" _lowerCAmelCase : int = text_classifier(a__ ) self.assertEqual(nested_simplify(a__ ) , [{"""label""": ANY(a__ ), """score""": ANY(a__ )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) _lowerCAmelCase : Optional[Any] = ["""HuggingFace is in """, """Paris is in France"""] _lowerCAmelCase : Optional[Any] = text_classifier(a__ ) self.assertEqual( nested_simplify(a__ ) , [{"""label""": ANY(a__ ), """score""": ANY(a__ )}, {"""label""": ANY(a__ ), """score""": ANY(a__ )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format _lowerCAmelCase : Dict = text_classifier(a__ , top_k=a__ ) _lowerCAmelCase : Optional[Any] = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(a__ ) , [[{"""label""": ANY(a__ ), """score""": ANY(a__ )}] * N, [{"""label""": ANY(a__ ), """score""": ANY(a__ )}] * N] , ) _lowerCAmelCase : str = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} _lowerCAmelCase : Dict = text_classifier(a__ ) self.assertEqual( nested_simplify(a__ ) , {"""label""": ANY(a__ ), """score""": ANY(a__ )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. _lowerCAmelCase : Any = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(a__ ): text_classifier(a__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility _lowerCAmelCase : Optional[Any] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(a__ ) , [{"""label""": ANY(a__ ), """score""": ANY(a__ )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
44
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _a : Dict = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , *a__ , **a__ ): super().__init__(*a__ , **a__ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , a__=None , a__=None , a__=None ): _lowerCAmelCase : List[str] = {} _lowerCAmelCase : Union[str, Any] = {} if prompt is not None: _lowerCAmelCase : List[Any] = prompt if generate_kwargs is not None: _lowerCAmelCase : List[str] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _lowerCAmelCase : str = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) _lowerCAmelCase : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , a__ , **a__ ): return super().__call__(a__ , **a__ ) def __A ( self , a__ , a__=None ): _lowerCAmelCase : Tuple = load_image(a__ ) if prompt is not None: if not isinstance(a__ , a__ ): raise ValueError( F"Received an invalid text input, got - {type(a__ )} - but expected a single string. " """Note also that one single text can be provided for conditional image to text generation.""" ) _lowerCAmelCase : Optional[int] = self.model.config.model_type if model_type == "git": _lowerCAmelCase : Optional[Any] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : List[str] = self.tokenizer(text=a__ , add_special_tokens=a__ ).input_ids _lowerCAmelCase : Union[str, Any] = [self.tokenizer.cls_token_id] + input_ids _lowerCAmelCase : Dict = torch.tensor(a__ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _lowerCAmelCase : Tuple = self.image_processor(images=a__ , header_text=a__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _lowerCAmelCase : Optional[int] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : Optional[int] = self.tokenizer(a__ , return_tensors=self.framework ) model_inputs.update(a__ ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: _lowerCAmelCase : Any = self.image_processor(images=a__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _lowerCAmelCase : Union[str, Any] = None return model_inputs def __A ( self , a__ , a__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , a__ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _lowerCAmelCase : Optional[int] = None if generate_kwargs is None: _lowerCAmelCase : List[str] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _lowerCAmelCase : Tuple = model_inputs.pop(self.model.main_input_name ) _lowerCAmelCase : Union[str, Any] = self.model.generate(a__ , **a__ , **a__ ) return model_outputs def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for output_ids in model_outputs: _lowerCAmelCase : Any = { """generated_text""": self.tokenizer.decode( a__ , skip_special_tokens=a__ , ) } records.append(a__ ) return records
44
1
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _a : Optional[Any] = logging.get_logger(__name__) _a : Optional[Any] = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "codegen" _UpperCamelCase : Tuple = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , a__=50400 , a__=2048 , a__=2048 , a__=4096 , a__=28 , a__=16 , a__=64 , a__=None , a__="gelu_new" , a__=0.0 , a__=0.0 , a__=0.0 , a__=1e-5 , a__=0.0_2 , a__=True , a__=50256 , a__=50256 , a__=False , **a__ , ): _lowerCAmelCase : Dict = vocab_size _lowerCAmelCase : Optional[Any] = n_ctx _lowerCAmelCase : Dict = n_positions _lowerCAmelCase : Any = n_embd _lowerCAmelCase : int = n_layer _lowerCAmelCase : Any = n_head _lowerCAmelCase : List[Any] = n_inner _lowerCAmelCase : int = rotary_dim _lowerCAmelCase : List[str] = activation_function _lowerCAmelCase : List[str] = resid_pdrop _lowerCAmelCase : Union[str, Any] = embd_pdrop _lowerCAmelCase : List[str] = attn_pdrop _lowerCAmelCase : Union[str, Any] = layer_norm_epsilon _lowerCAmelCase : Any = initializer_range _lowerCAmelCase : Union[str, Any] = use_cache _lowerCAmelCase : Union[str, Any] = bos_token_id _lowerCAmelCase : Optional[int] = eos_token_id super().__init__( bos_token_id=a__ , eos_token_id=a__ , tie_word_embeddings=a__ , **a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ = "default" , a__ = None , a__ = False , ): super().__init__(a__ , task=a__ , patching_specs=a__ , use_past=a__ ) if not getattr(self._config , """pad_token_id""" , a__ ): # TODO: how to do that better? _lowerCAmelCase : List[str] = 0 @property def __A ( self ): _lowerCAmelCase : Tuple = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(a__ , direction="""inputs""" ) _lowerCAmelCase : str = {0: """batch""", 1: """past_sequence + sequence"""} else: _lowerCAmelCase : List[Any] = {0: """batch""", 1: """sequence"""} return common_inputs @property def __A ( self ): return self._config.n_layer @property def __A ( self ): return self._config.n_head def __A ( self , a__ , a__ = -1 , a__ = -1 , a__ = False , a__ = None , ): _lowerCAmelCase : Any = super(a__ , self ).generate_dummy_inputs( a__ , batch_size=a__ , seq_length=a__ , is_pair=a__ , framework=a__ ) # We need to order the input in the way they appears in the forward() _lowerCAmelCase : Optional[int] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch _lowerCAmelCase , _lowerCAmelCase : Tuple = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values _lowerCAmelCase : Any = seqlen + 2 _lowerCAmelCase : int = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCAmelCase : Any = [ (torch.zeros(a__ ), torch.zeros(a__ )) for _ in range(self.num_layers ) ] _lowerCAmelCase : Union[str, Any] = common_inputs["""attention_mask"""] if self.use_past: _lowerCAmelCase : str = ordered_inputs["""attention_mask"""].dtype _lowerCAmelCase : int = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(a__ , a__ , dtype=a__ )] , dim=1 ) return ordered_inputs @property def __A ( self ): return 13
44
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _a : Dict = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.BuilderConfig ): _UpperCamelCase : int = 10_000 _UpperCamelCase : Optional[List[str]] = None _UpperCamelCase : Optional[datasets.Features] = None class __A ( datasets.ArrowBasedBuilder ): _UpperCamelCase : List[str] = ParquetConfig def __A ( self ): return datasets.DatasetInfo(features=self.config.features ) def __A ( self , a__ ): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) _lowerCAmelCase : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): _lowerCAmelCase : Any = data_files if isinstance(a__ , a__ ): _lowerCAmelCase : Tuple = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Any = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] _lowerCAmelCase : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): _lowerCAmelCase : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Tuple = [dl_manager.iter_files(a__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(a__ ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(a__ ) ) break splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , a__ ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _lowerCAmelCase : Optional[int] = table_cast(a__ , self.info.features.arrow_schema ) return pa_table def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Tuple = pq.ParquetFile(a__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): _lowerCAmelCase : Any = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(a__ ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : int ) -> str: if not isinstance(_lowerCamelCase ,_lowerCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(_lowerCamelCase ,_lowerCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) _lowerCAmelCase : Optional[int] = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_lowerCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) _a : Tuple = logging.getLogger(__name__) _a : Any = {'facebook/bart-base': BartForConditionalGeneration} _a : List[str] = {'facebook/bart-base': BartTokenizer} def SCREAMING_SNAKE_CASE ( ) -> int: _lowerCAmelCase : int = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" ,type=_lowerCamelCase ,default=5 ,help="""The maximum total input sequence length after tokenization.""" ,) parser.add_argument( """--num_beams""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) ,) parser.add_argument( """--model_name_or_path""" ,type=_lowerCamelCase ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=_lowerCamelCase ,) parser.add_argument( """--config_name""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Pretrained config name or path if not the same as model_name""" ,) parser.add_argument( """--device""" ,type=_lowerCamelCase ,default="""cpu""" ,help="""Device where the model will be run""" ,) parser.add_argument("""--output_file_path""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Where to store the final ONNX file.""" ) _lowerCAmelCase : Optional[Any] = parser.parse_args() return args def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Union[str, Any]="cpu" ) -> str: _lowerCAmelCase : List[str] = model_dict[model_name].from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = tokenizer_dict[model_name].from_pretrained(_lowerCamelCase ) if model_name in ["facebook/bart-base"]: _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : str = None _lowerCAmelCase : List[str] = 0 return huggingface_model, tokenizer def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : List[str] ,_lowerCamelCase : int ,_lowerCamelCase : List[Any] ,_lowerCamelCase : List[str] ) -> Tuple: model.eval() _lowerCAmelCase : str = None _lowerCAmelCase : int = torch.jit.script(BARTBeamSearchGenerator(_lowerCamelCase ) ) with torch.no_grad(): _lowerCAmelCase : List[Any] = """My friends are cool but they eat too many carbs.""" _lowerCAmelCase : Union[str, Any] = tokenizer([ARTICLE_TO_SUMMARIZE] ,max_length=1024 ,return_tensors="""pt""" ).to(model.device ) _lowerCAmelCase : Any = model.generate( inputs["""input_ids"""] ,attention_mask=inputs["""attention_mask"""] ,num_beams=_lowerCamelCase ,max_length=_lowerCamelCase ,early_stopping=_lowerCamelCase ,decoder_start_token_id=model.config.decoder_start_token_id ,) torch.onnx.export( _lowerCamelCase ,( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) ,_lowerCamelCase ,opset_version=14 ,input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] ,output_names=["""output_ids"""] ,dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } ,example_outputs=_lowerCamelCase ,) logger.info("""Model exported to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : List[str] = remove_dup_initializers(os.path.abspath(_lowerCamelCase ) ) logger.info("""Deduplicated and optimized model written to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : str = onnxruntime.InferenceSession(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = ort_sess.run( _lowerCamelCase ,{ """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(_lowerCamelCase ), """max_length""": np.array(_lowerCamelCase ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } ,) np.testing.assert_allclose(summary_ids.cpu().numpy() ,ort_out[0] ,rtol=1e-3 ,atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def SCREAMING_SNAKE_CASE ( ) -> Any: _lowerCAmelCase : Any = parse_args() _lowerCAmelCase : List[Any] = 5 _lowerCAmelCase : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO ,) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _lowerCAmelCase : Optional[Any] = torch.device(args.device ) _lowerCAmelCase , _lowerCAmelCase : List[str] = load_model_tokenizer(args.model_name_or_path ,_lowerCamelCase ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(_lowerCamelCase ) if args.max_length: _lowerCAmelCase : Dict = args.max_length if args.num_beams: _lowerCAmelCase : Dict = args.num_beams if args.output_file_path: _lowerCAmelCase : Any = args.output_file_path else: _lowerCAmelCase : Union[str, Any] = """BART.onnx""" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if __name__ == "__main__": main()
44
1
"""simple docstring""" import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py _a : Optional[Any] = 'src/transformers' _a : Any = 'docs/source/en/tasks' def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ) -> int: with open(_lowerCamelCase ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: _lowerCAmelCase : List[str] = f.readlines() # Find the start prompt. _lowerCAmelCase : Any = 0 while not lines[start_index].startswith(_lowerCamelCase ): start_index += 1 start_index += 1 _lowerCAmelCase : List[Any] = start_index while not lines[end_index].startswith(_lowerCamelCase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. _a : Union[str, Any] = direct_transformers_import(TRANSFORMERS_PATH) _a : Optional[int] = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). _a : Tuple = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ) -> Optional[int]: _lowerCAmelCase : int = TASK_GUIDE_TO_MODELS[task_guide] _lowerCAmelCase : Any = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_lowerCamelCase ,set() ) _lowerCAmelCase : List[Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f"[{name}](../model_doc/{code})" for code, name in model_names.items()] ) + "\n" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Optional[Any]=False ) -> Dict: _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = _find_text_in_file( filename=os.path.join(_lowerCamelCase ,_lowerCamelCase ) ,start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" ,end_prompt="""<!--End of the generated tip-->""" ,) _lowerCAmelCase : Any = get_model_list_for_task(_lowerCamelCase ) if current_list != new_list: if overwrite: with open(os.path.join(_lowerCamelCase ,_lowerCamelCase ) ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`" """ to fix this.""" ) if __name__ == "__main__": _a : List[str] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _a : Dict = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ) -> List[Any]: # noqa: E741 _lowerCAmelCase : Optional[int] = len(_lowerCamelCase ) _lowerCAmelCase : str = 0 _lowerCAmelCase : Any = [0] * n _lowerCAmelCase : str = [False] * n _lowerCAmelCase : str = [False] * n def dfs(_lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ): if parent == root: out_edge_count += 1 _lowerCAmelCase : Any = True _lowerCAmelCase : int = at for to in l[at]: if to == parent: pass elif not visited[to]: _lowerCAmelCase : Union[str, Any] = dfs(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Optional[int] = min(low[at] ,low[to] ) # AP found via bridge if at < low[to]: _lowerCAmelCase : int = True # AP found via cycle if at == low[to]: _lowerCAmelCase : Tuple = True else: _lowerCAmelCase : Union[str, Any] = min(low[at] ,_lowerCamelCase ) return out_edge_count for i in range(_lowerCamelCase ): if not visited[i]: _lowerCAmelCase : int = 0 _lowerCAmelCase : Dict = dfs(_lowerCamelCase ,_lowerCamelCase ,-1 ,_lowerCamelCase ) _lowerCAmelCase : List[str] = out_edge_count > 1 for x in range(len(_lowerCamelCase ) ): if is_art[x] is True: print(_lowerCamelCase ) # Adjacency list of graph _a : Optional[Any] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
44
1
"""simple docstring""" import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : str = (DPMSolverSDEScheduler,) _UpperCamelCase : Optional[int] = 10 def __A ( self , **a__ ): _lowerCAmelCase : Optional[int] = { """num_train_timesteps""": 1100, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**a__ ) return config def __A ( self ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __A ( self ): for beta_start, beta_end in zip([0.0_0_0_0_1, 0.0_0_0_1, 0.0_0_1] , [0.0_0_0_2, 0.0_0_2, 0.0_2] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __A ( self ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __A ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __A ( self ): _lowerCAmelCase : Tuple = self.scheduler_classes[0] _lowerCAmelCase : Any = self.get_scheduler_config() _lowerCAmelCase : Tuple = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) _lowerCAmelCase : int = self.dummy_model() _lowerCAmelCase : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma _lowerCAmelCase : int = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): _lowerCAmelCase : int = scheduler.scale_model_input(a__ , a__ ) _lowerCAmelCase : Optional[int] = model(a__ , a__ ) _lowerCAmelCase : List[Any] = scheduler.step(a__ , a__ , a__ ) _lowerCAmelCase : Dict = output.prev_sample _lowerCAmelCase : Dict = torch.sum(torch.abs(a__ ) ) _lowerCAmelCase : Optional[Any] = torch.mean(torch.abs(a__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_6_7.4_7_8_2_1_0_4_4_9_2_1_8_7_5 ) < 1e-2 assert abs(result_mean.item() - 0.2_1_7_8_7_0_5_9_6_4_5_6_5_2_7_7 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_1.5_9_3_5_2_1_1_1_8_1_6_4_0_6 ) < 1e-2 assert abs(result_mean.item() - 0.2_2_3_4_2_9_0_6_8_9_2_2_9_9_6_5_2 ) < 1e-3 else: assert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1e-2 assert abs(result_mean.item() - 0.2_1_1_6_1_9_5_7_0_8_5_1_3_2_6 ) < 1e-3 def __A ( self ): _lowerCAmelCase : Dict = self.scheduler_classes[0] _lowerCAmelCase : str = self.get_scheduler_config(prediction_type="""v_prediction""" ) _lowerCAmelCase : Union[str, Any] = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) _lowerCAmelCase : Any = self.dummy_model() _lowerCAmelCase : List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma _lowerCAmelCase : List[Any] = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): _lowerCAmelCase : int = scheduler.scale_model_input(a__ , a__ ) _lowerCAmelCase : int = model(a__ , a__ ) _lowerCAmelCase : List[str] = scheduler.step(a__ , a__ , a__ ) _lowerCAmelCase : Optional[int] = output.prev_sample _lowerCAmelCase : Any = torch.sum(torch.abs(a__ ) ) _lowerCAmelCase : str = torch.mean(torch.abs(a__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_2_4.7_7_1_4_9_2_0_0_4_3_9_4_5_3 ) < 1e-2 assert abs(result_mean.item() - 0.1_6_2_2_6_2_8_9_0_1_4_8_1_6_2_8_4 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_2_8.1_6_6_3_3_6_0_5_9_5_7_0_3 ) < 1e-2 assert abs(result_mean.item() - 0.1_6_6_8_8_3_2_6_0_0_1_1_6_7_2_9_7 ) < 1e-3 else: assert abs(result_sum.item() - 1_1_9.8_4_8_7_5_4_8_8_2_8_1_2_5 ) < 1e-2 assert abs(result_mean.item() - 0.1_5_6_0_5_3_0_6_6_2_5_3_6_6_2_1 ) < 1e-3 def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.scheduler_classes[0] _lowerCAmelCase : Optional[Any] = self.get_scheduler_config() _lowerCAmelCase : str = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) _lowerCAmelCase : Tuple = self.dummy_model() _lowerCAmelCase : Optional[Any] = self.dummy_sample_deter.to(a__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _lowerCAmelCase : Union[str, Any] = scheduler.scale_model_input(a__ , a__ ) _lowerCAmelCase : Tuple = model(a__ , a__ ) _lowerCAmelCase : Optional[int] = scheduler.step(a__ , a__ , a__ ) _lowerCAmelCase : List[str] = output.prev_sample _lowerCAmelCase : int = torch.sum(torch.abs(a__ ) ) _lowerCAmelCase : List[str] = torch.mean(torch.abs(a__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_6_7.4_6_9_5_7_3_9_7_4_6_0_9_3_8 ) < 1e-2 assert abs(result_mean.item() - 0.2_1_8_0_5_9_3_4_6_0_7_9_8_2_6_3_5 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_1.5_9_3_5_3_6_3_7_6_9_5_3_1_2 ) < 1e-2 assert abs(result_mean.item() - 0.2_2_3_4_2_9_0_8_3_8_2_4_1_5_7_7_1 ) < 1e-3 else: assert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1e-2 assert abs(result_mean.item() - 0.2_1_1_6_1_9_5_7_0_8_5_1_3_2_6 ) < 1e-3 def __A ( self ): _lowerCAmelCase : Any = self.scheduler_classes[0] _lowerCAmelCase : Dict = self.get_scheduler_config() _lowerCAmelCase : Optional[int] = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) _lowerCAmelCase : Any = self.dummy_model() _lowerCAmelCase : int = self.dummy_sample_deter.to(a__ ) * scheduler.init_noise_sigma _lowerCAmelCase : int = sample.to(a__ ) for t in scheduler.timesteps: _lowerCAmelCase : Optional[Any] = scheduler.scale_model_input(a__ , a__ ) _lowerCAmelCase : Optional[int] = model(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = scheduler.step(a__ , a__ , a__ ) _lowerCAmelCase : Tuple = output.prev_sample _lowerCAmelCase : List[Any] = torch.sum(torch.abs(a__ ) ) _lowerCAmelCase : Dict = torch.mean(torch.abs(a__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_7_6.6_6_9_7_4_1_3_5_7_4_2_1_8_8 ) < 1e-2 assert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_7.6_3_6_5_3_5_6_4_4_5_3_1_2_5 ) < 1e-2 assert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1e-2 else: assert abs(result_sum.item() - 1_7_0.3_1_3_5_2_2_3_3_8_8_6_7_2 ) < 1e-2 assert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1e-2
44
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = XGLMTokenizer _UpperCamelCase : List[Any] = XGLMTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : Tuple = True def __A ( self ): super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[str] = """<pad>""" _lowerCAmelCase : List[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 __A ( self ): _lowerCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(a__ ) , 1008 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __A ( self ): _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Any = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def __A ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) _lowerCAmelCase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=a__ ) _lowerCAmelCase : List[str] = pickle.dumps(a__ ) pickle.loads(a__ ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = self.get_rust_tokenizer() _lowerCAmelCase : Tuple = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : List[Any] = tokenizer.tokenize(a__ ) _lowerCAmelCase : Tuple = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : str = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = self.get_rust_tokenizer() _lowerCAmelCase : Dict = tokenizer.encode(a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __A ( self ): _lowerCAmelCase : int = """Hello World!""" _lowerCAmelCase : Optional[int] = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Any = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _lowerCAmelCase : List[str] = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : List[str] = { """input_ids""": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/xglm-564M""" , padding=a__ , )
44
1
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
44
"""simple docstring""" from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : int ) -> List[str]: _lowerCAmelCase : Tuple = k_size // 2 _lowerCAmelCase , _lowerCAmelCase : List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] _lowerCAmelCase : Union[str, Any] = 1 / (2 * pi * sigma) * exp(-(square(_lowerCamelCase ) + square(_lowerCamelCase )) / (2 * square(_lowerCamelCase )) ) return g def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> Dict: _lowerCAmelCase , _lowerCAmelCase : str = image.shape[0], image.shape[1] # dst image height and width _lowerCAmelCase : Optional[int] = height - k_size + 1 _lowerCAmelCase : Dict = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows _lowerCAmelCase : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) _lowerCAmelCase : int = 0 for i, j in product(range(_lowerCamelCase ) ,range(_lowerCamelCase ) ): _lowerCAmelCase : Any = ravel(image[i : i + k_size, j : j + k_size] ) _lowerCAmelCase : Union[str, Any] = window row += 1 # turn the kernel into shape(k*k, 1) _lowerCAmelCase : List[Any] = gen_gaussian_kernel(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = ravel(_lowerCamelCase ) # reshape and get the dst image _lowerCAmelCase : int = dot(_lowerCamelCase ,_lowerCamelCase ).reshape(_lowerCamelCase ,_lowerCamelCase ).astype(_lowerCamelCase ) return dst if __name__ == "__main__": # read original image _a : Optional[Any] = imread(r'../image_data/lena.jpg') # turn image in gray scale value _a : Dict = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _a : Union[str, Any] = gaussian_filter(gray, 3, sigma=1) _a : List[Any] = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
44
1
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar _a : Any = TypeVar('T') class __A ( Generic[T] ): _UpperCamelCase : deque[T] # Cache store of keys _UpperCamelCase : set[T] # References of the keys in cache _UpperCamelCase : int = 10 # Maximum capacity of cache def __init__( self , a__ ): _lowerCAmelCase : Any = deque() _lowerCAmelCase : List[Any] = set() if not n: _lowerCAmelCase : List[str] = sys.maxsize elif n < 0: raise ValueError("""n should be an integer greater than 0.""" ) else: _lowerCAmelCase : List[Any] = n def __A ( self , a__ ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: _lowerCAmelCase : Dict = self.dq_store.pop() self.key_reference.remove(a__ ) else: self.dq_store.remove(a__ ) self.dq_store.appendleft(a__ ) self.key_reference.add(a__ ) def __A ( self ): for k in self.dq_store: print(a__ ) def __repr__( self ): return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() _a : LRUCache[str | int] = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
44
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
1
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer _a : str = logging.get_logger(__name__) _a : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : int = { 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } _a : int = { 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } _a : List[str] = { 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } _a : List[str] = { 'facebook/dpr-ctx_encoder-single-nq-base': 512, 'facebook/dpr-ctx_encoder-multiset-base': 512, } _a : Optional[Any] = { 'facebook/dpr-question_encoder-single-nq-base': 512, 'facebook/dpr-question_encoder-multiset-base': 512, } _a : Union[str, Any] = { 'facebook/dpr-reader-single-nq-base': 512, 'facebook/dpr-reader-multiset-base': 512, } _a : Optional[int] = { 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } _a : Any = { 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } _a : Dict = { 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[int] = VOCAB_FILES_NAMES _UpperCamelCase : Optional[int] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[str] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : int = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Tuple = DPRContextEncoderTokenizer class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Any = VOCAB_FILES_NAMES _UpperCamelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : Tuple = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : List[Any] = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Tuple = DPRQuestionEncoderTokenizer _a : List[Any] = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) _a : Tuple = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) _a : List[str] = r'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(SCREAMING_SNAKE_CASE_ ) class __A : def __call__( self , a__ , a__ = None , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , **a__ , ): if titles is None and texts is None: return super().__call__( a__ , padding=a__ , truncation=a__ , max_length=a__ , return_tensors=a__ , return_attention_mask=a__ , **a__ , ) elif titles is None or texts is None: _lowerCAmelCase : Union[str, Any] = titles if texts is None else texts return super().__call__( a__ , a__ , padding=a__ , truncation=a__ , max_length=a__ , return_tensors=a__ , return_attention_mask=a__ , **a__ , ) _lowerCAmelCase : Union[str, Any] = titles if not isinstance(a__ , a__ ) else [titles] _lowerCAmelCase : List[Any] = texts if not isinstance(a__ , a__ ) else [texts] _lowerCAmelCase : Union[str, Any] = len(a__ ) _lowerCAmelCase : Union[str, Any] = questions if not isinstance(a__ , a__ ) else [questions] * n_passages assert len(a__ ) == len( a__ ), F"There should be as many titles than texts but got {len(a__ )} titles and {len(a__ )} texts." _lowerCAmelCase : str = super().__call__(a__ , a__ , padding=a__ , truncation=a__ )["""input_ids"""] _lowerCAmelCase : str = super().__call__(a__ , add_special_tokens=a__ , padding=a__ , truncation=a__ )["""input_ids"""] _lowerCAmelCase : Dict = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(a__ , a__ ) ] } if return_attention_mask is not False: _lowerCAmelCase : Tuple = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _lowerCAmelCase : Optional[Any] = attention_mask return self.pad(a__ , padding=a__ , max_length=a__ , return_tensors=a__ ) def __A ( self , a__ , a__ , a__ = 16 , a__ = 64 , a__ = 4 , ): _lowerCAmelCase : Dict = reader_input["""input_ids"""] _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = reader_output[:3] _lowerCAmelCase : List[str] = len(a__ ) _lowerCAmelCase : Union[str, Any] = sorted(range(a__ ) , reverse=a__ , key=relevance_logits.__getitem__ ) _lowerCAmelCase : List[DPRReaderOutput] = [] for doc_id in sorted_docs: _lowerCAmelCase : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _lowerCAmelCase : List[str] = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _lowerCAmelCase : List[str] = sequence_ids.index(self.pad_token_id ) else: _lowerCAmelCase : Tuple = len(a__ ) _lowerCAmelCase : int = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=a__ , top_spans=a__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=a__ , start_index=a__ , end_index=a__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(a__ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def __A ( self , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : List[str] = [] for start_index, start_score in enumerate(a__ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _lowerCAmelCase : Optional[Any] = sorted(a__ , key=lambda a__ : x[1] , reverse=a__ ) _lowerCAmelCase : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F"Wrong span indices: [{start_index}:{end_index}]" _lowerCAmelCase : Union[str, Any] = end_index - start_index + 1 assert length <= max_answer_length, F"Span is too long: {length} > {max_answer_length}" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(a__ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Any = VOCAB_FILES_NAMES _UpperCamelCase : Optional[Any] = READER_PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = READER_PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : int = ["input_ids", "attention_mask"] _UpperCamelCase : Optional[int] = DPRReaderTokenizer
44
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ , a__ , a__ = None , ): super().__init__() self.register_modules(transformer=a__ , vae=a__ , scheduler=a__ ) # create a imagenet -> id dictionary for easier use _lowerCAmelCase : Optional[int] = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(""",""" ): _lowerCAmelCase : Any = int(a__ ) _lowerCAmelCase : List[Any] = dict(sorted(self.labels.items() ) ) def __A ( self , a__ ): if not isinstance(a__ , a__ ): _lowerCAmelCase : Union[str, Any] = list(a__ ) for l in label: if l not in self.labels: raise ValueError( F"{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}." ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self , a__ , a__ = 4.0 , a__ = None , a__ = 50 , a__ = "pil" , a__ = True , ): _lowerCAmelCase : Optional[int] = len(a__ ) _lowerCAmelCase : Union[str, Any] = self.transformer.config.sample_size _lowerCAmelCase : str = self.transformer.config.in_channels _lowerCAmelCase : Any = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=a__ , device=self.device , dtype=self.transformer.dtype , ) _lowerCAmelCase : Optional[int] = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents _lowerCAmelCase : Any = torch.tensor(a__ , device=self.device ).reshape(-1 ) _lowerCAmelCase : List[str] = torch.tensor([1000] * batch_size , device=self.device ) _lowerCAmelCase : int = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(a__ ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: _lowerCAmelCase : Dict = latent_model_input[: len(a__ ) // 2] _lowerCAmelCase : Any = torch.cat([half, half] , dim=0 ) _lowerCAmelCase : Dict = self.scheduler.scale_model_input(a__ , a__ ) _lowerCAmelCase : List[str] = t if not torch.is_tensor(a__ ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) _lowerCAmelCase : List[Any] = latent_model_input.device.type == """mps""" if isinstance(a__ , a__ ): _lowerCAmelCase : List[Any] = torch.floataa if is_mps else torch.floataa else: _lowerCAmelCase : Tuple = torch.intaa if is_mps else torch.intaa _lowerCAmelCase : Union[str, Any] = torch.tensor([timesteps] , dtype=a__ , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: _lowerCAmelCase : Any = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _lowerCAmelCase : Union[str, Any] = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output _lowerCAmelCase : str = self.transformer( a__ , timestep=a__ , class_labels=a__ ).sample # perform guidance if guidance_scale > 1: _lowerCAmelCase , _lowerCAmelCase : Any = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] _lowerCAmelCase , _lowerCAmelCase : List[str] = torch.split(a__ , len(a__ ) // 2 , dim=0 ) _lowerCAmelCase : Union[str, Any] = uncond_eps + guidance_scale * (cond_eps - uncond_eps) _lowerCAmelCase : Any = torch.cat([half_eps, half_eps] , dim=0 ) _lowerCAmelCase : List[Any] = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: _lowerCAmelCase , _lowerCAmelCase : str = torch.split(a__ , a__ , dim=1 ) else: _lowerCAmelCase : Any = noise_pred # compute previous image: x_t -> x_t-1 _lowerCAmelCase : str = self.scheduler.step(a__ , a__ , a__ ).prev_sample if guidance_scale > 1: _lowerCAmelCase , _lowerCAmelCase : Any = latent_model_input.chunk(2 , dim=0 ) else: _lowerCAmelCase : List[Any] = latent_model_input _lowerCAmelCase : Union[str, Any] = 1 / self.vae.config.scaling_factor * latents _lowerCAmelCase : Optional[Any] = self.vae.decode(a__ ).sample _lowerCAmelCase : Optional[int] = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _lowerCAmelCase : List[str] = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(a__ ) if not return_dict: return (samples,) return ImagePipelineOutput(images=a__ )
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
1
"""simple docstring""" import os import pytest from attr import dataclass _a : Optional[int] = 'us-east-1' # defaults region @dataclass class __A : _UpperCamelCase : str _UpperCamelCase : Any = "arn:aws:iam::558105141721:role/sagemaker_execution_role" _UpperCamelCase : Tuple = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5_500, } _UpperCamelCase : List[str] = {**hyperparameters, "max_steps": 1_000} @property def __A ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __A ( self ): return F"{self.framework}-transfromers-test" @property def __A ( self ): return F"./tests/sagemaker/scripts/{self.framework}" @property def __A ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="""class""" ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> List[str]: _lowerCAmelCase : Optional[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
44
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
1
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> bool: if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) _lowerCAmelCase : List[str] = sorted(string.lower() ) return len(_lowerCamelCase ) == len(set(_lowerCamelCase ) ) if __name__ == "__main__": _a : List[Any] = input('Enter a string ').strip() _a : Union[str, Any] = is_isogram(input_str) print(F"""{input_str} is {"an" if isogram else "not an"} isogram.""")
44
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
44
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Any = "Salesforce/blip-image-captioning-base" _UpperCamelCase : str = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) _UpperCamelCase : List[Any] = "image_captioner" _UpperCamelCase : List[Any] = AutoModelForVisionaSeq _UpperCamelCase : str = ["image"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): requires_backends(self , ["""vision"""] ) super().__init__(*a__ , **a__ ) def __A ( self , a__ ): return self.pre_processor(images=a__ , return_tensors="""pt""" ) def __A ( self , a__ ): return self.model.generate(**a__ ) def __A ( self , a__ ): return self.pre_processor.batch_decode(a__ , skip_special_tokens=a__ )[0].strip()
44
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Dict = parent _lowerCAmelCase : str = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Dict = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Any = hidden_dropout_prob _lowerCAmelCase : List[str] = attention_probs_dropout_prob _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : Tuple = type_sequence_label_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Tuple = relative_attention _lowerCAmelCase : Tuple = position_biased_input _lowerCAmelCase : Dict = pos_att_type _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCAmelCase : str = None if self.use_token_type_ids: _lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return 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 , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self , a__ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] _lowerCAmelCase : List[Any] = model(a__ , token_type_ids=a__ )[0] _lowerCAmelCase : Any = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = DebertaVaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : int = self.num_labels _lowerCAmelCase : int = DebertaVaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = DebertaVaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = DebertaVaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _UpperCamelCase : str = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = True _UpperCamelCase : List[Any] = False _UpperCamelCase : List[Any] = False _UpperCamelCase : Dict = False _UpperCamelCase : Tuple = False def __A ( self ): _lowerCAmelCase : Optional[Any] = DebertaVaModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*a__ ) @slow def __A ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Tuple = DebertaVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def __A ( self ): pass @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) _lowerCAmelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _lowerCAmelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. _lowerCAmelCase : str = torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F"{output[:, 1:4, 1:4]}" )
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ) -> bool: if not isinstance(_lowerCamelCase ,_lowerCamelCase ): raise ValueError("""check_bouncy() accepts only integer arguments""" ) _lowerCAmelCase : Any = str(_lowerCamelCase ) _lowerCAmelCase : List[Any] = """""".join(sorted(_lowerCamelCase ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def SCREAMING_SNAKE_CASE ( _lowerCamelCase : float = 99 ) -> int: if not 0 < percent < 100: raise ValueError("""solution() only accepts values from 0 to 100""" ) _lowerCAmelCase : int = 0 _lowerCAmelCase : str = 1 while True: if check_bouncy(_lowerCamelCase ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(99)}""")
44
"""simple docstring""" import numpy as np import qiskit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 8 ,_lowerCamelCase : int | None = None ) -> str: _lowerCAmelCase : int = np.random.default_rng(seed=_lowerCamelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. _lowerCAmelCase : Dict = rng.integers(2 ,size=_lowerCamelCase ) # The set of states Alice will prepare. _lowerCAmelCase : Tuple = rng.integers(2 ,size=_lowerCamelCase ) # Measurement basis for Bob's qubits. _lowerCAmelCase : Union[str, Any] = rng.integers(2 ,size=_lowerCamelCase ) # Quantum Circuit to simulate BB84 _lowerCAmelCase : Dict = qiskit.QuantumCircuit(_lowerCamelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCamelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCAmelCase : int = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCAmelCase : List[str] = qiskit.execute(_lowerCamelCase ,_lowerCamelCase ,shots=1 ,seed_simulator=_lowerCamelCase ) # Returns the result of measurement. _lowerCAmelCase : List[Any] = job.result().get_counts(_lowerCamelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCAmelCase : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCAmelCase : List[Any] = gen_key[:key_len] if len(_lowerCamelCase ) >= key_len else gen_key.ljust(_lowerCamelCase ,"""0""" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
44
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_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""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): 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 __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _a : Union[str, Any] = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _a : List[str] = 10 _a : List[Any] = 256 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[MinHash]: if len(_lowerCamelCase ) < MIN_NUM_TOKENS: return None _lowerCAmelCase : Optional[Any] = MinHash(num_perm=_lowerCamelCase ) for token in set(_lowerCamelCase ): min_hash.update(token.encode() ) return min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> Set[str]: return {t for t in NON_ALPHA.split(_lowerCamelCase ) if len(t.strip() ) > 0} class __A : def __init__( self , *, a__ = 0.8_5 , ): _lowerCAmelCase : List[Any] = duplication_jaccard_threshold _lowerCAmelCase : Union[str, Any] = NUM_PERM _lowerCAmelCase : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase : Optional[int] = defaultdict(a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[Any] = self._index.query(a__ ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(a__ , a__ ) if len(a__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(a__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(a__ ) def __A ( self ): _lowerCAmelCase : int = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase : List[str] = [base] + list(a__ ) # reformat the cluster to be a list of dict _lowerCAmelCase : List[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(a__ ) return duplicate_clusters def __A ( self , a__ ): _lowerCAmelCase : Dict = self.get_duplicate_clusters() with open(a__ , """w""" ) as f: json.dump(a__ , a__ ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : Tuple = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ) -> Optional[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash ,ThreadedIterator(_lowerCamelCase ,max_queue_size=10000 ) ,chunksize=100 ,): if data is not None: yield data def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float ) -> List[str]: _lowerCAmelCase : Optional[Any] = DuplicationIndex(duplication_jaccard_threshold=_lowerCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_lowerCamelCase ) ) ,max_queue_size=100 ) ): di.add(_lowerCamelCase ,_lowerCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> float: _lowerCAmelCase : Any = get_tokens(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = get_tokens(_lowerCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _a : str = None def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : List[Any] ) -> Dict: _lowerCAmelCase : int = [] for elementa in cluster: _lowerCAmelCase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: _lowerCAmelCase : Any = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(_lowerCamelCase ,_lowerCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase : Any = 1 extremes.append(_lowerCamelCase ) return extremes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Any ) -> str: global _shared_dataset _lowerCAmelCase : Tuple = dataset _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Optional[Any] = partial(_find_cluster_extremes_shared ,jaccard_threshold=_lowerCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _lowerCamelCase ,_lowerCamelCase ,) ,total=len(_lowerCamelCase ) ,): extremes_list.append(_lowerCamelCase ) return extremes_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase : Tuple = make_duplicate_clusters(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase : Optional[int] = {} _lowerCAmelCase : Tuple = find_extremes(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : List[Any] = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase : List[Any] = dataset.filter(lambda _lowerCamelCase ,_lowerCamelCase : idx not in remove_indices ,with_indices=_lowerCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase : Tuple = element["""base_index"""] in extreme_dict if element["is_extreme"]: _lowerCAmelCase : Dict = extreme_dict[element["""base_index"""]]["""copies"""] print(f"Original dataset size: {len(_lowerCamelCase )}" ) print(f"Number of duplicate clusters: {len(_lowerCamelCase )}" ) print(f"Files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Filtered dataset size: {len(_lowerCamelCase )}" ) return ds_filter, duplicate_clusters
44
1
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _a : Union[str, Any] = logging.get_logger(__name__) _a : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } _a : Optional[int] = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } _a : Tuple = {'facebook/blenderbot-3B': 128} class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Any = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Union[str, Any] = ["input_ids", "attention_mask"] _UpperCamelCase : Optional[int] = BlenderbotTokenizer def __init__( self , a__=None , a__=None , a__=None , a__="replace" , a__="<s>" , a__="</s>" , a__="</s>" , a__="<s>" , a__="<unk>" , a__="<pad>" , a__="<mask>" , a__=False , a__=True , **a__ , ): super().__init__( a__ , a__ , tokenizer_file=a__ , errors=a__ , bos_token=a__ , eos_token=a__ , sep_token=a__ , cls_token=a__ , unk_token=a__ , pad_token=a__ , mask_token=a__ , add_prefix_space=a__ , trim_offsets=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , a__ ) != add_prefix_space: _lowerCAmelCase : int = getattr(a__ , pre_tok_state.pop("""type""" ) ) _lowerCAmelCase : Optional[Any] = add_prefix_space _lowerCAmelCase : List[Any] = pre_tok_class(**a__ ) _lowerCAmelCase : List[str] = add_prefix_space _lowerCAmelCase : Dict = """post_processor""" _lowerCAmelCase : List[Any] = getattr(self.backend_tokenizer , a__ , a__ ) if tokenizer_component_instance: _lowerCAmelCase : Any = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _lowerCAmelCase : List[Any] = tuple(state["""sep"""] ) if "cls" in state: _lowerCAmelCase : Tuple = tuple(state["""cls"""] ) _lowerCAmelCase : Union[str, Any] = False if state.get("""add_prefix_space""" , a__ ) != add_prefix_space: _lowerCAmelCase : Any = add_prefix_space _lowerCAmelCase : Optional[Any] = True if state.get("""trim_offsets""" , a__ ) != trim_offsets: _lowerCAmelCase : Any = trim_offsets _lowerCAmelCase : List[str] = True if changes_to_apply: _lowerCAmelCase : Union[str, Any] = getattr(a__ , state.pop("""type""" ) ) _lowerCAmelCase : Union[str, Any] = component_class(**a__ ) setattr(self.backend_tokenizer , a__ , a__ ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def __A ( self ): if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def __A ( self , a__ ): _lowerCAmelCase : Optional[Any] = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else value _lowerCAmelCase : List[str] = value def __A ( self , *a__ , **a__ ): _lowerCAmelCase : int = kwargs.get("""is_split_into_words""" , a__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a__ , **a__ ) def __A ( self , *a__ , **a__ ): _lowerCAmelCase : str = kwargs.get("""is_split_into_words""" , a__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a__ , **a__ ) def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Union[str, Any] = [self.sep_token_id] _lowerCAmelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __A ( self , a__ , a__ = None ): return token_ids_a + [self.eos_token_id] def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(""" """ + text ) else: # Generated responses should contain them already. inputs.append(a__ ) _lowerCAmelCase : Union[str, Any] = """ """.join(a__ ) _lowerCAmelCase : Tuple = self.encode(a__ ) if len(a__ ) > self.model_max_length: _lowerCAmelCase : List[Any] = input_ids[-self.model_max_length :] logger.warning(F"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
44
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
1
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
44
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
1
"""simple docstring""" _a : Tuple = 'Input must be a string of 8 numbers plus letter' _a : Optional[int] = 'TRWAGMYFPDXBNJZSQVHLCKE' def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> bool: if not isinstance(_lowerCamelCase ,_lowerCamelCase ): _lowerCAmelCase : Any = f"Expected string as input, found {type(_lowerCamelCase ).__name__}" raise TypeError(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = spanish_id.replace("""-""" ,"""""" ).upper() if len(_lowerCamelCase ) != 9: raise ValueError(_lowerCamelCase ) try: _lowerCAmelCase : List[str] = int(spanish_id_clean[0:8] ) _lowerCAmelCase : Any = spanish_id_clean[8] except ValueError as ex: raise ValueError(_lowerCamelCase ) from ex if letter.isdigit(): raise ValueError(_lowerCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : List[Any] = torch.exp(_lowerCamelCase ) _lowerCAmelCase : List[Any] = torch.sum(_lowerCamelCase ,dim=1 ) # sum of exp(x_i) _lowerCAmelCase : Dict = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : int = config.output_attentions _lowerCAmelCase : Any = config.output_hidden_states _lowerCAmelCase : List[Any] = nn.ModuleList([BertLayer(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : Any = nn.ModuleList([BertHighway(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : str = [-1 for _ in range(config.num_hidden_layers )] def __A ( self , a__ ): if (type(a__ ) is float) or (type(a__ ) is int): for i in range(len(self.early_exit_entropy ) ): _lowerCAmelCase : Tuple = x else: _lowerCAmelCase : Optional[int] = x def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __A ( self , a__ , a__=None , a__=None , a__=None , a__=None , ): _lowerCAmelCase : Any = () _lowerCAmelCase : Optional[int] = () _lowerCAmelCase : List[Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _lowerCAmelCase : str = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[str] = layer_module( a__ , a__ , head_mask[i] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = layer_outputs[0] if self.output_attentions: _lowerCAmelCase : Dict = all_attentions + (layer_outputs[1],) _lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Optional[int] = current_outputs + (all_attentions,) _lowerCAmelCase : Optional[Any] = self.highway[i](a__ ) # logits, pooled_output if not self.training: _lowerCAmelCase : Tuple = highway_exit[0] _lowerCAmelCase : Any = entropy(a__ ) _lowerCAmelCase : Optional[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _lowerCAmelCase : Union[str, Any] = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _lowerCAmelCase : List[str] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a__ , i + 1 ) else: _lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _lowerCAmelCase : List[Any] = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[Any] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : List[str] = outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Any = outputs + (all_attentions,) _lowerCAmelCase : Optional[int] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config _lowerCAmelCase : Tuple = BertEmbeddings(a__ ) _lowerCAmelCase : Tuple = DeeBertEncoder(a__ ) _lowerCAmelCase : List[str] = BertPooler(a__ ) self.init_weights() def __A ( self ): self.encoder.init_highway_pooler(self.pooler ) def __A ( self ): return self.embeddings.word_embeddings def __A ( self , a__ ): _lowerCAmelCase : Dict = value def __A ( self , a__ ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a__ ) @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _lowerCAmelCase : Any = input_ids.size() elif inputs_embeds is not None: _lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _lowerCAmelCase : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _lowerCAmelCase : List[Any] = torch.ones(a__ , device=a__ ) if encoder_attention_mask is None: _lowerCAmelCase : Optional[Any] = torch.ones(a__ , device=a__ ) if token_type_ids is None: _lowerCAmelCase : Dict = torch.zeros(a__ , dtype=torch.long , device=a__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(a__ , a__ , a__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _lowerCAmelCase : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _lowerCAmelCase : Tuple = encoder_attention_mask[:, None, None, :] _lowerCAmelCase : Union[str, Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _lowerCAmelCase : Optional[Any] = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _lowerCAmelCase : Optional[int] = self.get_head_mask(a__ , self.config.num_hidden_layers ) _lowerCAmelCase : Dict = self.embeddings( input_ids=a__ , position_ids=a__ , token_type_ids=a__ , inputs_embeds=a__ ) _lowerCAmelCase : Union[str, Any] = self.encoder( a__ , attention_mask=a__ , head_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Dict = encoder_outputs[0] _lowerCAmelCase : Union[str, Any] = self.pooler(a__ ) _lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ ): _lowerCAmelCase : str = message _lowerCAmelCase : str = exit_layer # start from 1! class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Any = BertPooler(a__ ) _lowerCAmelCase : str = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def __A ( self , a__ ): # Pooler _lowerCAmelCase : Tuple = encoder_outputs[0] _lowerCAmelCase : int = self.pooler(a__ ) # "return" pooler_output # BertModel _lowerCAmelCase : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _lowerCAmelCase : Optional[int] = bmodel_output[1] _lowerCAmelCase : Tuple = self.dropout(a__ ) _lowerCAmelCase : Dict = self.classifier(a__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[str] = config.num_labels _lowerCAmelCase : Optional[Any] = config.num_hidden_layers _lowerCAmelCase : str = DeeBertModel(a__ ) _lowerCAmelCase : Tuple = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : List[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=-1 , a__=False , ): _lowerCAmelCase : Dict = self.num_layers try: _lowerCAmelCase : str = self.bert( a__ , attention_mask=a__ , token_type_ids=a__ , position_ids=a__ , head_mask=a__ , inputs_embeds=a__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _lowerCAmelCase : Any = outputs[1] _lowerCAmelCase : Optional[int] = self.dropout(a__ ) _lowerCAmelCase : List[str] = self.classifier(a__ ) _lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : int = e.exit_layer _lowerCAmelCase : Union[str, Any] = outputs[0] if not self.training: _lowerCAmelCase : Tuple = entropy(a__ ) _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Tuple = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase : Optional[Any] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Dict = highway_exit[0] if not self.training: highway_logits_all.append(a__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Optional[int] = CrossEntropyLoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(a__ ) if train_highway: _lowerCAmelCase : List[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Dict = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Dict = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
1
"""simple docstring""" import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[int] = StableUnCLIPPipeline _UpperCamelCase : Optional[Any] = TEXT_TO_IMAGE_PARAMS _UpperCamelCase : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS _UpperCamelCase : str = TEXT_TO_IMAGE_IMAGE_PARAMS _UpperCamelCase : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _UpperCamelCase : Optional[Any] = False def __A ( self ): _lowerCAmelCase : Any = 32 _lowerCAmelCase : str = embedder_hidden_size # prior components torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) torch.manual_seed(0 ) _lowerCAmelCase : str = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=a__ , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=a__ , num_layers=1 , ) torch.manual_seed(0 ) _lowerCAmelCase : Optional[Any] = DDPMScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=a__ , clip_sample_range=5.0 , beta_schedule="""squaredcos_cap_v2""" , ) # regular denoising components torch.manual_seed(0 ) _lowerCAmelCase : Any = StableUnCLIPImageNormalizer(embedding_dim=a__ ) _lowerCAmelCase : int = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" ) torch.manual_seed(0 ) _lowerCAmelCase : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _lowerCAmelCase : Tuple = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="""projection""" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a__ , layers_per_block=1 , upcast_attention=a__ , use_linear_projection=a__ , ) torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = DDIMScheduler( beta_schedule="""scaled_linear""" , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type="""v_prediction""" , set_alpha_to_one=a__ , steps_offset=1 , ) torch.manual_seed(0 ) _lowerCAmelCase : str = AutoencoderKL() _lowerCAmelCase : Any = { # prior components """prior_tokenizer""": prior_tokenizer, """prior_text_encoder""": prior_text_encoder, """prior""": prior, """prior_scheduler""": prior_scheduler, # image noising components """image_normalizer""": image_normalizer, """image_noising_scheduler""": image_noising_scheduler, # regular denoising components """tokenizer""": tokenizer, """text_encoder""": text_encoder, """unet""": unet, """scheduler""": scheduler, """vae""": vae, } return components def __A ( self , a__ , a__=0 ): if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : Optional[int] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : List[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """prior_num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def __A ( self ): _lowerCAmelCase : Optional[Any] = torch_device == """cpu""" self._test_attention_slicing_forward_pass(test_max_difference=a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = torch_device in ["""cpu""", """mps"""] self._test_inference_batch_single_identical(test_max_difference=a__ ) @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Optional[int] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy""" ) _lowerCAmelCase : Optional[Any] = StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l""" , torch_dtype=torch.floataa ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowerCAmelCase : str = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase : Tuple = pipe("""anime turle""" , generator=a__ , output_type="""np""" ) _lowerCAmelCase : Optional[int] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ ) def __A ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCAmelCase : Optional[int] = StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l""" , torch_dtype=torch.floataa ) _lowerCAmelCase : int = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowerCAmelCase : Any = pipe( """anime turtle""" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="""np""" , ) _lowerCAmelCase : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
44
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : str = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , a__ = None , a__ = None , **a__ , ): super().__init__(self , **a__ ) _lowerCAmelCase : Any = repo_info _lowerCAmelCase : Optional[Any] = token _lowerCAmelCase : Optional[int] = None def __A ( self ): if self.dir_cache is None: _lowerCAmelCase : Optional[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowerCAmelCase : 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 __A ( self , a__ , a__ = "rb" , **a__ , ): if not isinstance(self.repo_info , a__ ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) _lowerCAmelCase : Tuple = 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 __A ( self , a__ , **a__ ): self._get_dirs() _lowerCAmelCase : Union[str, Any] = self._strip_protocol(a__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a__ ) def __A ( self , a__ , a__=False , **a__ ): self._get_dirs() _lowerCAmelCase : Any = PurePosixPath(path.strip("""/""" ) ) _lowerCAmelCase : List[str] = {} for p, f in self.dir_cache.items(): _lowerCAmelCase : Any = PurePosixPath(p.strip("""/""" ) ) _lowerCAmelCase : Optional[int] = p.parent if root == path: _lowerCAmelCase : Dict = f _lowerCAmelCase : Union[str, Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
44
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : Tuple = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : List[str] = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _a : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_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""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): 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 __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
1
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ) -> typing.Counter[int]: _lowerCAmelCase : typing.Counter[int] = Counter() for base in range(1 ,max_perimeter + 1 ): for perpendicular in range(_lowerCamelCase ,max_perimeter + 1 ): _lowerCAmelCase : Optional[int] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(_lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 1000 ) -> int: _lowerCAmelCase : int = pythagorean_triple(_lowerCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(F"""Perimeter {solution()} has maximum solutions""")
44
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
1
"""simple docstring""" from math import factorial class __A : def __init__( self , a__ , a__ ): _lowerCAmelCase : Dict = real if isinstance(a__ , a__ ): _lowerCAmelCase : int = [1] * rank else: _lowerCAmelCase : int = rank def __repr__( self ): return ( F"{self.real}+" F"{'+'.join(str(a__ )+'E'+str(n+1 )for n,dual in enumerate(self.duals ) )}" ) def __A ( self ): _lowerCAmelCase : str = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real , a__ ) def __add__( self , a__ ): if not isinstance(a__ , a__ ): return Dual(self.real + other , self.duals ) _lowerCAmelCase : List[str] = self.duals.copy() _lowerCAmelCase : Optional[int] = other.duals.copy() if len(a__ ) > len(a__ ): o_dual.extend([1] * (len(a__ ) - len(a__ )) ) elif len(a__ ) < len(a__ ): s_dual.extend([1] * (len(a__ ) - len(a__ )) ) _lowerCAmelCase : List[str] = [] for i in range(len(a__ ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real , a__ ) _UpperCamelCase : Optional[Any] = __add__ def __sub__( self , a__ ): return self + other * -1 def __mul__( self , a__ ): if not isinstance(a__ , a__ ): _lowerCAmelCase : Any = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other , a__ ) _lowerCAmelCase : Union[str, Any] = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , a__ ) _UpperCamelCase : Optional[Any] = __mul__ def __truediv__( self , a__ ): if not isinstance(a__ , a__ ): _lowerCAmelCase : Tuple = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other , a__ ) raise ValueError def __floordiv__( self , a__ ): if not isinstance(a__ , a__ ): _lowerCAmelCase : List[str] = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other , a__ ) raise ValueError def __pow__( self , a__ ): if n < 0 or isinstance(a__ , a__ ): raise ValueError("""power must be a positive integer""" ) if n == 0: return 1 if n == 1: return self _lowerCAmelCase : Union[str, Any] = self for _ in range(n - 1 ): x *= self return x def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : int ,_lowerCamelCase : List[str] ) -> Tuple: if not callable(_lowerCamelCase ): raise ValueError("""differentiate() requires a function as input for func""" ) if not isinstance(_lowerCamelCase ,(float, int) ): raise ValueError("""differentiate() requires a float as input for position""" ) if not isinstance(_lowerCamelCase ,_lowerCamelCase ): raise ValueError("""differentiate() requires an int as input for order""" ) _lowerCAmelCase : int = Dual(_lowerCamelCase ,1 ) _lowerCAmelCase : str = func(_lowerCamelCase ) if order == 0: return result.real return result.duals[order - 1] * factorial(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ) -> Dict: return y**2 * y**4 print(differentiate(f, 9, 2))
44
"""simple docstring""" _a : List[str] = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.13.2', 'requests-mock': 'requests-mock==1.10.0', 'importlib_metadata': 'importlib_metadata', 'invisible-watermark': 'invisible-watermark', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2', 'jaxlib': 'jaxlib>=0.1.65', 'Jinja2': 'Jinja2', 'k-diffusion': 'k-diffusion>=0.0.12', 'torchsde': 'torchsde', 'note_seq': 'note_seq', 'librosa': 'librosa', 'numpy': 'numpy', 'omegaconf': 'omegaconf', 'parameterized': 'parameterized', 'protobuf': 'protobuf>=3.20.3,<4', 'pytest': 'pytest', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'ruff': 'ruff>=0.0.241', 'safetensors': 'safetensors', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'scipy': 'scipy', 'onnx': 'onnx', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'tensorboard': 'tensorboard', 'torch': 'torch>=1.4', 'torchvision': 'torchvision', 'transformers': 'transformers>=4.25.1', 'urllib3': 'urllib3<=2.0.0', }
44
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _a : Union[str, Any] = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _a : List[Any] = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _a : List[Any] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_000)) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> tuple[str, float]: _lowerCAmelCase : List[Any] = len([g for position, g in enumerate(_lowerCamelCase ) if g == main_target[position]] ) return (item, float(_lowerCamelCase )) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> tuple[str, str]: _lowerCAmelCase : Dict = random.randint(0 ,len(_lowerCamelCase ) - 1 ) _lowerCAmelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] _lowerCAmelCase : Optional[int] = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : list[str] ) -> str: _lowerCAmelCase : Optional[Any] = list(_lowerCamelCase ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _lowerCAmelCase : Optional[int] = random.choice(_lowerCamelCase ) return "".join(_lowerCamelCase ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : tuple[str, float] ,_lowerCamelCase : list[tuple[str, float]] ,_lowerCamelCase : list[str] ,) -> list[str]: _lowerCAmelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _lowerCAmelCase : Optional[Any] = int(parent_a[1] * 100 ) + 1 _lowerCAmelCase : Dict = 10 if child_n >= 10 else child_n for _ in range(_lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = population_score[random.randint(0 ,_lowerCamelCase )][0] _lowerCAmelCase , _lowerCAmelCase : int = crossover(parent_a[0] ,_lowerCamelCase ) # Append new string to the population list. pop.append(mutate(_lowerCamelCase ,_lowerCamelCase ) ) pop.append(mutate(_lowerCamelCase ,_lowerCamelCase ) ) return pop def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : list[str] ,_lowerCamelCase : bool = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: _lowerCAmelCase : Any = f"{N_POPULATION} must be bigger than {N_SELECTED}" raise ValueError(_lowerCamelCase ) # Verify that the target contains no genes besides the ones inside genes variable. _lowerCAmelCase : Dict = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _lowerCAmelCase : Optional[int] = f"{not_in_genes_list} is not in genes list, evolution cannot converge" raise ValueError(_lowerCamelCase ) # Generate random starting population. _lowerCAmelCase : Optional[int] = [] for _ in range(_lowerCamelCase ): population.append("""""".join([random.choice(_lowerCamelCase ) for i in range(len(_lowerCamelCase ) )] ) ) # Just some logs to know what the algorithms is doing. _lowerCAmelCase , _lowerCAmelCase : Tuple = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(_lowerCamelCase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _lowerCAmelCase : Dict = [evaluate(_lowerCamelCase ,_lowerCamelCase ) for item in population] # Check if there is a matching evolution. _lowerCAmelCase : List[str] = sorted(_lowerCamelCase ,key=lambda _lowerCamelCase : x[1] ,reverse=_lowerCamelCase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _lowerCAmelCase : Optional[int] = population[: int(N_POPULATION / 3 )] population.clear() population.extend(_lowerCamelCase ) # Normalize population score to be between 0 and 1. _lowerCAmelCase : Optional[int] = [ (item, score / len(_lowerCamelCase )) for item, score in population_score ] # This is selection for i in range(_lowerCamelCase ): population.extend(select(population_score[int(_lowerCamelCase )] ,_lowerCamelCase ,_lowerCamelCase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(_lowerCamelCase ) > N_POPULATION: break if __name__ == "__main__": _a : Dict = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) _a : Tuple = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) _a , _a , _a : str = basic(target_str, genes_list) print( F"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
44
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _a : Dict = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , *a__ , **a__ ): super().__init__(*a__ , **a__ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , a__=None , a__=None , a__=None ): _lowerCAmelCase : List[str] = {} _lowerCAmelCase : Union[str, Any] = {} if prompt is not None: _lowerCAmelCase : List[Any] = prompt if generate_kwargs is not None: _lowerCAmelCase : List[str] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _lowerCAmelCase : str = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) _lowerCAmelCase : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , a__ , **a__ ): return super().__call__(a__ , **a__ ) def __A ( self , a__ , a__=None ): _lowerCAmelCase : Tuple = load_image(a__ ) if prompt is not None: if not isinstance(a__ , a__ ): raise ValueError( F"Received an invalid text input, got - {type(a__ )} - but expected a single string. " """Note also that one single text can be provided for conditional image to text generation.""" ) _lowerCAmelCase : Optional[int] = self.model.config.model_type if model_type == "git": _lowerCAmelCase : Optional[Any] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : List[str] = self.tokenizer(text=a__ , add_special_tokens=a__ ).input_ids _lowerCAmelCase : Union[str, Any] = [self.tokenizer.cls_token_id] + input_ids _lowerCAmelCase : Dict = torch.tensor(a__ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _lowerCAmelCase : Tuple = self.image_processor(images=a__ , header_text=a__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _lowerCAmelCase : Optional[int] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : Optional[int] = self.tokenizer(a__ , return_tensors=self.framework ) model_inputs.update(a__ ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: _lowerCAmelCase : Any = self.image_processor(images=a__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _lowerCAmelCase : Union[str, Any] = None return model_inputs def __A ( self , a__ , a__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , a__ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _lowerCAmelCase : Optional[int] = None if generate_kwargs is None: _lowerCAmelCase : List[str] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _lowerCAmelCase : Tuple = model_inputs.pop(self.model.main_input_name ) _lowerCAmelCase : Union[str, Any] = self.model.generate(a__ , **a__ , **a__ ) return model_outputs def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for output_ids in model_outputs: _lowerCAmelCase : Any = { """generated_text""": self.tokenizer.decode( a__ , skip_special_tokens=a__ , ) } records.append(a__ ) return records
44
1
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex _a : Any = logging.getLogger(__name__) class __A : def __init__( self ): _lowerCAmelCase : Tuple = False def __A ( self , a__ , a__ , a__ , a__ ): if not self.initialized: _lowerCAmelCase : Any = RagRetriever( a__ , question_encoder_tokenizer=a__ , generator_tokenizer=a__ , index=a__ , init_retrieval=a__ , ) _lowerCAmelCase : Optional[int] = True def __A ( self ): self.retriever.index.init_index() def __A ( self , a__ , a__ ): _lowerCAmelCase , _lowerCAmelCase : Any = self.retriever._main_retrieve(a__ , a__ ) return doc_ids, retrieved_doc_embeds class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ , a__ , a__ , a__=None ): if index is not None and index.is_initialized() and len(a__ ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( a__ , question_encoder_tokenizer=a__ , generator_tokenizer=a__ , index=a__ , init_retrieval=a__ , ) _lowerCAmelCase : Union[str, Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(a__ , a__ , a__ , a__ ) for worker in self.retrieval_workers ] ) def __A ( self ): logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __A ( self , a__ , a__ ): if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. _lowerCAmelCase : List[str] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] _lowerCAmelCase , _lowerCAmelCase : Tuple = ray.get(random_worker.retrieve.remote(a__ , a__ ) ) else: _lowerCAmelCase , _lowerCAmelCase : Any = self._main_retrieve(a__ , a__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a__ ) @classmethod def __A ( cls , a__ , a__=None , **a__ ): return super(a__ , cls ).get_tokenizers(a__ , a__ , **a__ ) @classmethod def __A ( cls , a__ , a__ , a__=None , **a__ ): _lowerCAmelCase : str = kwargs.pop("""config""" , a__ ) or RagConfig.from_pretrained(a__ , **a__ ) _lowerCAmelCase : Tuple = RagTokenizer.from_pretrained(a__ , config=a__ ) _lowerCAmelCase : str = rag_tokenizer.question_encoder _lowerCAmelCase : Union[str, Any] = rag_tokenizer.generator if indexed_dataset is not None: _lowerCAmelCase : Any = """custom""" _lowerCAmelCase : Any = CustomHFIndex(config.retrieval_vector_size , a__ ) else: _lowerCAmelCase : Union[str, Any] = cls._build_index(a__ ) return cls( a__ , question_encoder_tokenizer=a__ , generator_tokenizer=a__ , retrieval_workers=a__ , index=a__ , )
44
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _a : Dict = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.BuilderConfig ): _UpperCamelCase : int = 10_000 _UpperCamelCase : Optional[List[str]] = None _UpperCamelCase : Optional[datasets.Features] = None class __A ( datasets.ArrowBasedBuilder ): _UpperCamelCase : List[str] = ParquetConfig def __A ( self ): return datasets.DatasetInfo(features=self.config.features ) def __A ( self , a__ ): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) _lowerCAmelCase : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): _lowerCAmelCase : Any = data_files if isinstance(a__ , a__ ): _lowerCAmelCase : Tuple = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Any = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] _lowerCAmelCase : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): _lowerCAmelCase : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Tuple = [dl_manager.iter_files(a__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(a__ ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(a__ ) ) break splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , a__ ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _lowerCAmelCase : Optional[int] = table_cast(a__ , self.info.features.arrow_schema ) return pa_table def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Tuple = pq.ParquetFile(a__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): _lowerCAmelCase : Any = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(a__ ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
44
1
"""simple docstring""" from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
44
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) _a : Tuple = logging.getLogger(__name__) _a : Any = {'facebook/bart-base': BartForConditionalGeneration} _a : List[str] = {'facebook/bart-base': BartTokenizer} def SCREAMING_SNAKE_CASE ( ) -> int: _lowerCAmelCase : int = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" ,type=_lowerCamelCase ,default=5 ,help="""The maximum total input sequence length after tokenization.""" ,) parser.add_argument( """--num_beams""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) ,) parser.add_argument( """--model_name_or_path""" ,type=_lowerCamelCase ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=_lowerCamelCase ,) parser.add_argument( """--config_name""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Pretrained config name or path if not the same as model_name""" ,) parser.add_argument( """--device""" ,type=_lowerCamelCase ,default="""cpu""" ,help="""Device where the model will be run""" ,) parser.add_argument("""--output_file_path""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Where to store the final ONNX file.""" ) _lowerCAmelCase : Optional[Any] = parser.parse_args() return args def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Union[str, Any]="cpu" ) -> str: _lowerCAmelCase : List[str] = model_dict[model_name].from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = tokenizer_dict[model_name].from_pretrained(_lowerCamelCase ) if model_name in ["facebook/bart-base"]: _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : str = None _lowerCAmelCase : List[str] = 0 return huggingface_model, tokenizer def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : List[str] ,_lowerCamelCase : int ,_lowerCamelCase : List[Any] ,_lowerCamelCase : List[str] ) -> Tuple: model.eval() _lowerCAmelCase : str = None _lowerCAmelCase : int = torch.jit.script(BARTBeamSearchGenerator(_lowerCamelCase ) ) with torch.no_grad(): _lowerCAmelCase : List[Any] = """My friends are cool but they eat too many carbs.""" _lowerCAmelCase : Union[str, Any] = tokenizer([ARTICLE_TO_SUMMARIZE] ,max_length=1024 ,return_tensors="""pt""" ).to(model.device ) _lowerCAmelCase : Any = model.generate( inputs["""input_ids"""] ,attention_mask=inputs["""attention_mask"""] ,num_beams=_lowerCamelCase ,max_length=_lowerCamelCase ,early_stopping=_lowerCamelCase ,decoder_start_token_id=model.config.decoder_start_token_id ,) torch.onnx.export( _lowerCamelCase ,( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) ,_lowerCamelCase ,opset_version=14 ,input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] ,output_names=["""output_ids"""] ,dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } ,example_outputs=_lowerCamelCase ,) logger.info("""Model exported to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : List[str] = remove_dup_initializers(os.path.abspath(_lowerCamelCase ) ) logger.info("""Deduplicated and optimized model written to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : str = onnxruntime.InferenceSession(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = ort_sess.run( _lowerCamelCase ,{ """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(_lowerCamelCase ), """max_length""": np.array(_lowerCamelCase ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } ,) np.testing.assert_allclose(summary_ids.cpu().numpy() ,ort_out[0] ,rtol=1e-3 ,atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def SCREAMING_SNAKE_CASE ( ) -> Any: _lowerCAmelCase : Any = parse_args() _lowerCAmelCase : List[Any] = 5 _lowerCAmelCase : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO ,) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _lowerCAmelCase : Optional[Any] = torch.device(args.device ) _lowerCAmelCase , _lowerCAmelCase : List[str] = load_model_tokenizer(args.model_name_or_path ,_lowerCamelCase ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(_lowerCamelCase ) if args.max_length: _lowerCAmelCase : Dict = args.max_length if args.num_beams: _lowerCAmelCase : Dict = args.num_beams if args.output_file_path: _lowerCAmelCase : Any = args.output_file_path else: _lowerCAmelCase : Union[str, Any] = """BART.onnx""" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if __name__ == "__main__": main()
44
1
"""simple docstring""" from __future__ import annotations def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ,_lowerCamelCase : list[int] ,_lowerCamelCase : int ) -> tuple[float, list[float]]: _lowerCAmelCase : List[str] = list(range(len(_lowerCamelCase ) ) ) _lowerCAmelCase : int = [v / w for v, w in zip(_lowerCamelCase ,_lowerCamelCase )] index.sort(key=lambda _lowerCamelCase : ratio[i] ,reverse=_lowerCamelCase ) _lowerCAmelCase : float = 0 _lowerCAmelCase : list[float] = [0] * len(_lowerCamelCase ) for i in index: if weight[i] <= capacity: _lowerCAmelCase : Dict = 1 max_value += value[i] capacity -= weight[i] else: _lowerCAmelCase : Any = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ) -> List[Any]: # noqa: E741 _lowerCAmelCase : Optional[int] = len(_lowerCamelCase ) _lowerCAmelCase : str = 0 _lowerCAmelCase : Any = [0] * n _lowerCAmelCase : str = [False] * n _lowerCAmelCase : str = [False] * n def dfs(_lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ): if parent == root: out_edge_count += 1 _lowerCAmelCase : Any = True _lowerCAmelCase : int = at for to in l[at]: if to == parent: pass elif not visited[to]: _lowerCAmelCase : Union[str, Any] = dfs(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Optional[int] = min(low[at] ,low[to] ) # AP found via bridge if at < low[to]: _lowerCAmelCase : int = True # AP found via cycle if at == low[to]: _lowerCAmelCase : Tuple = True else: _lowerCAmelCase : Union[str, Any] = min(low[at] ,_lowerCamelCase ) return out_edge_count for i in range(_lowerCamelCase ): if not visited[i]: _lowerCAmelCase : int = 0 _lowerCAmelCase : Dict = dfs(_lowerCamelCase ,_lowerCamelCase ,-1 ,_lowerCamelCase ) _lowerCAmelCase : List[str] = out_edge_count > 1 for x in range(len(_lowerCamelCase ) ): if is_art[x] is True: print(_lowerCamelCase ) # Adjacency list of graph _a : Optional[Any] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
44
1
"""simple docstring""" # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests _a : List[Any] = open # noqa: we just need to have a builtin inside this module to test it properly
44
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = XGLMTokenizer _UpperCamelCase : List[Any] = XGLMTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : Tuple = True def __A ( self ): super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[str] = """<pad>""" _lowerCAmelCase : List[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 __A ( self ): _lowerCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(a__ ) , 1008 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __A ( self ): _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Any = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def __A ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) _lowerCAmelCase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=a__ ) _lowerCAmelCase : List[str] = pickle.dumps(a__ ) pickle.loads(a__ ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = self.get_rust_tokenizer() _lowerCAmelCase : Tuple = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : List[Any] = tokenizer.tokenize(a__ ) _lowerCAmelCase : Tuple = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : str = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = self.get_rust_tokenizer() _lowerCAmelCase : Dict = tokenizer.encode(a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __A ( self ): _lowerCAmelCase : int = """Hello World!""" _lowerCAmelCase : Optional[int] = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Any = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _lowerCAmelCase : List[str] = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : List[str] = { """input_ids""": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/xglm-564M""" , padding=a__ , )
44
1
"""simple docstring""" _a : Tuple = tuple[float, float, float] _a : Union[str, Any] = tuple[float, float, float] def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Pointad ,_lowerCamelCase : Pointad ) -> Vectorad: _lowerCAmelCase : str = end_pointa[0] - end_pointa[0] _lowerCAmelCase : Union[str, Any] = end_pointa[1] - end_pointa[1] _lowerCAmelCase : Dict = end_pointa[2] - end_pointa[2] return (x, y, z) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Vectorad ,_lowerCamelCase : Vectorad ) -> Vectorad: _lowerCAmelCase : Any = ab[1] * ac[2] - ab[2] * ac[1] # *i _lowerCAmelCase : Tuple = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j _lowerCAmelCase : str = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Vectorad ,_lowerCamelCase : int ) -> bool: return tuple(round(_lowerCamelCase ,_lowerCamelCase ) for x in vector ) == (0, 0, 0) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Pointad ,_lowerCamelCase : Pointad ,_lowerCamelCase : Pointad ,_lowerCamelCase : int = 10 ) -> bool: _lowerCAmelCase : str = create_vector(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Optional[int] = create_vector(_lowerCamelCase ,_lowerCamelCase ) return is_zero_vector(get_ad_vectors_cross(_lowerCamelCase ,_lowerCamelCase ) ,_lowerCamelCase )
44
"""simple docstring""" from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : int ) -> List[str]: _lowerCAmelCase : Tuple = k_size // 2 _lowerCAmelCase , _lowerCAmelCase : List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] _lowerCAmelCase : Union[str, Any] = 1 / (2 * pi * sigma) * exp(-(square(_lowerCamelCase ) + square(_lowerCamelCase )) / (2 * square(_lowerCamelCase )) ) return g def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> Dict: _lowerCAmelCase , _lowerCAmelCase : str = image.shape[0], image.shape[1] # dst image height and width _lowerCAmelCase : Optional[int] = height - k_size + 1 _lowerCAmelCase : Dict = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows _lowerCAmelCase : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) _lowerCAmelCase : int = 0 for i, j in product(range(_lowerCamelCase ) ,range(_lowerCamelCase ) ): _lowerCAmelCase : Any = ravel(image[i : i + k_size, j : j + k_size] ) _lowerCAmelCase : Union[str, Any] = window row += 1 # turn the kernel into shape(k*k, 1) _lowerCAmelCase : List[Any] = gen_gaussian_kernel(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = ravel(_lowerCamelCase ) # reshape and get the dst image _lowerCAmelCase : int = dot(_lowerCamelCase ,_lowerCamelCase ).reshape(_lowerCamelCase ,_lowerCamelCase ).astype(_lowerCamelCase ) return dst if __name__ == "__main__": # read original image _a : Optional[Any] = imread(r'../image_data/lena.jpg') # turn image in gray scale value _a : Dict = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _a : Union[str, Any] = gaussian_filter(gray, 3, sigma=1) _a : List[Any] = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
44
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf 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 ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class __A : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=[1, 1, 2] , a__=1 , a__=32 , a__=4 , a__=8 , a__=37 , a__="gelu_new" , a__=0.1 , a__=0.1 , a__=0.0 , a__=512 , a__=3 , a__=0.0_2 , a__=3 , a__=4 , a__=None , a__=False , ): _lowerCAmelCase : Union[str, Any] = parent _lowerCAmelCase : Optional[Any] = batch_size _lowerCAmelCase : Optional[Any] = seq_length _lowerCAmelCase : Union[str, Any] = is_training _lowerCAmelCase : List[Any] = use_input_mask _lowerCAmelCase : List[Any] = use_token_type_ids _lowerCAmelCase : List[Any] = use_labels _lowerCAmelCase : List[Any] = vocab_size _lowerCAmelCase : Any = block_sizes _lowerCAmelCase : List[str] = num_decoder_layers _lowerCAmelCase : List[Any] = d_model _lowerCAmelCase : List[Any] = n_head _lowerCAmelCase : Any = d_head _lowerCAmelCase : Union[str, Any] = d_inner _lowerCAmelCase : Optional[int] = hidden_act _lowerCAmelCase : Optional[Any] = hidden_dropout _lowerCAmelCase : Optional[int] = attention_dropout _lowerCAmelCase : int = activation_dropout _lowerCAmelCase : str = max_position_embeddings _lowerCAmelCase : Optional[Any] = type_vocab_size _lowerCAmelCase : Optional[Any] = 2 _lowerCAmelCase : List[str] = num_labels _lowerCAmelCase : Dict = num_choices _lowerCAmelCase : Optional[int] = scope _lowerCAmelCase : List[str] = initializer_std # Used in the tests to check the size of the first attention layer _lowerCAmelCase : Dict = n_head # Used in the tests to check the size of the first hidden state _lowerCAmelCase : Union[str, Any] = self.d_model # Used in the tests to check the number of output hidden states/attentions _lowerCAmelCase : List[Any] = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: _lowerCAmelCase : List[Any] = self.num_hidden_layers + 2 def __A ( self ): _lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Dict = None if self.use_input_mask: _lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase : Dict = None if self.use_token_type_ids: _lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Dict = None _lowerCAmelCase : Dict = None _lowerCAmelCase : Tuple = None if self.use_labels: _lowerCAmelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : Tuple = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : List[str] = TFFunnelModel(config=a__ ) _lowerCAmelCase : Any = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : List[Any] = model(a__ ) _lowerCAmelCase : Tuple = [input_ids, input_mask] _lowerCAmelCase : List[str] = model(a__ ) _lowerCAmelCase : Any = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _lowerCAmelCase : str = False _lowerCAmelCase : List[str] = TFFunnelModel(config=a__ ) _lowerCAmelCase : Optional[int] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _lowerCAmelCase : int = False _lowerCAmelCase : Tuple = TFFunnelModel(config=a__ ) _lowerCAmelCase : int = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Optional[Any] = TFFunnelBaseModel(config=a__ ) _lowerCAmelCase : Dict = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : Any = model(a__ ) _lowerCAmelCase : Optional[int] = [input_ids, input_mask] _lowerCAmelCase : Any = model(a__ ) _lowerCAmelCase : Optional[int] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) _lowerCAmelCase : List[Any] = False _lowerCAmelCase : int = TFFunnelBaseModel(config=a__ ) _lowerCAmelCase : List[str] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) _lowerCAmelCase : Any = False _lowerCAmelCase : Optional[Any] = TFFunnelBaseModel(config=a__ ) _lowerCAmelCase : Dict = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Union[str, Any] = TFFunnelForPreTraining(config=a__ ) _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : Optional[int] = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Any = TFFunnelForMaskedLM(config=a__ ) _lowerCAmelCase : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : List[str] = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Optional[int] = self.num_labels _lowerCAmelCase : List[str] = TFFunnelForSequenceClassification(config=a__ ) _lowerCAmelCase : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : List[Any] = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : List[str] = self.num_choices _lowerCAmelCase : Dict = TFFunnelForMultipleChoice(config=a__ ) _lowerCAmelCase : Any = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) ) _lowerCAmelCase : int = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) ) _lowerCAmelCase : str = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) ) _lowerCAmelCase : List[str] = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } _lowerCAmelCase : List[str] = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Tuple = self.num_labels _lowerCAmelCase : List[Any] = TFFunnelForTokenClassification(config=a__ ) _lowerCAmelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : Dict = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): _lowerCAmelCase : Tuple = TFFunnelForQuestionAnswering(config=a__ ) _lowerCAmelCase : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _lowerCAmelCase : 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 __A ( self ): _lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : str = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Dict = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) _UpperCamelCase : int = ( { "feature-extraction": (TFFunnelBaseModel, TFFunnelModel), "fill-mask": TFFunnelForMaskedLM, "question-answering": TFFunnelForQuestionAnswering, "text-classification": TFFunnelForSequenceClassification, "token-classification": TFFunnelForTokenClassification, "zero-shot": TFFunnelForSequenceClassification, } if is_tf_available() else {} ) _UpperCamelCase : List[str] = False _UpperCamelCase : List[str] = False def __A ( self ): _lowerCAmelCase : Dict = TFFunnelModelTester(self ) _lowerCAmelCase : Union[str, Any] = ConfigTester(self , config_class=a__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a__ ) @require_tf class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[str] = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) _UpperCamelCase : Optional[Any] = False _UpperCamelCase : Optional[Any] = False def __A ( self ): _lowerCAmelCase : Tuple = TFFunnelModelTester(self , base=a__ ) _lowerCAmelCase : List[Any] = ConfigTester(self , config_class=a__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a__ )
44
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : Union[str, Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[int] = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys _a : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
1
"""simple docstring""" _a : dict[str, float] = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr": 4_186_800.00, "electronvolt": 1.6_02_17_66_34e-19, "britishthermalunit_it": 1_055.05_585, "footpound": 1.35_58_18, } def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ,_lowerCamelCase : float ) -> float: if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: _lowerCAmelCase : Union[str, Any] = ( f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Valid values are: {', '.join(_lowerCamelCase )}" ) raise ValueError(_lowerCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
1
"""simple docstring""" from argparse import ArgumentParser from .env import EnvironmentCommand def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: _lowerCAmelCase : Optional[Any] = ArgumentParser("""Diffusers CLI tool""" ,usage="""diffusers-cli <command> [<args>]""" ) _lowerCAmelCase : Optional[int] = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_lowerCamelCase ) # Let's go _lowerCAmelCase : Union[str, Any] = parser.parse_args() if not hasattr(_lowerCamelCase ,"""func""" ): parser.print_help() exit(1 ) # Run _lowerCAmelCase : Dict = args.func(_lowerCamelCase ) service.run() if __name__ == "__main__": main()
44
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
1
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
1
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __A ( unittest.TestCase ): def __init__( self , a__ , a__=7 , a__=3 , a__=30 , a__=400 , a__=True , a__=None , a__=True , a__=[0.5, 0.5, 0.5] , a__=[0.5, 0.5, 0.5] , a__=True , a__=1 / 255 , a__=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _lowerCAmelCase : int = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} _lowerCAmelCase : List[str] = parent _lowerCAmelCase : Dict = batch_size _lowerCAmelCase : int = num_channels _lowerCAmelCase : Optional[Any] = min_resolution _lowerCAmelCase : Tuple = max_resolution _lowerCAmelCase : List[Any] = do_resize _lowerCAmelCase : Optional[Any] = size _lowerCAmelCase : Optional[int] = do_normalize _lowerCAmelCase : Optional[int] = image_mean _lowerCAmelCase : Dict = image_std _lowerCAmelCase : Optional[Any] = do_rescale _lowerCAmelCase : List[Any] = rescale_factor _lowerCAmelCase : int = do_pad def __A ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __A ( self , a__ , a__=False ): if not batched: _lowerCAmelCase : Optional[int] = image_inputs[0] if isinstance(a__ , Image.Image ): _lowerCAmelCase , _lowerCAmelCase : str = image.size else: _lowerCAmelCase , _lowerCAmelCase : Tuple = image.shape[1], image.shape[2] if w < h: _lowerCAmelCase : Any = int(self.size["""shortest_edge"""] * h / w ) _lowerCAmelCase : Optional[int] = self.size["""shortest_edge"""] elif w > h: _lowerCAmelCase : Tuple = self.size["""shortest_edge"""] _lowerCAmelCase : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h ) else: _lowerCAmelCase : List[Any] = self.size["""shortest_edge"""] _lowerCAmelCase : Any = self.size["""shortest_edge"""] else: _lowerCAmelCase : Optional[int] = [] for image in image_inputs: _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _lowerCAmelCase : List[str] = max(a__ , key=lambda a__ : item[0] )[0] _lowerCAmelCase : Any = max(a__ , key=lambda a__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Tuple = ConditionalDetrImageProcessor if is_vision_available() else None def __A ( self ): _lowerCAmelCase : Dict = ConditionalDetrImageProcessingTester(self ) @property def __A ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ): _lowerCAmelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a__ , """image_mean""" ) ) self.assertTrue(hasattr(a__ , """image_std""" ) ) self.assertTrue(hasattr(a__ , """do_normalize""" ) ) self.assertTrue(hasattr(a__ , """do_resize""" ) ) self.assertTrue(hasattr(a__ , """size""" ) ) def __A ( self ): _lowerCAmelCase : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad , a__ ) _lowerCAmelCase : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a__ ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , a__ ) def __A ( self ): pass def __A ( self ): # Initialize image_processing _lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ ) for image in image_inputs: self.assertIsInstance(a__ , Image.Image ) # Test not batched input _lowerCAmelCase : str = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : str = self.image_processor_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.image_processor_tester.get_expected_values(a__ , batched=a__ ) _lowerCAmelCase : Optional[Any] = image_processing(a__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ): # Initialize image_processing _lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , numpify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , np.ndarray ) # Test not batched input _lowerCAmelCase : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.image_processor_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase : str = image_processing(a__ , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : int = self.image_processor_tester.get_expected_values(a__ , batched=a__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ): # Initialize image_processing _lowerCAmelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase : Tuple = 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 _lowerCAmelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.image_processor_tester.get_expected_values(a__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase : Tuple = image_processing(a__ , return_tensors="""pt""" ).pixel_values _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.image_processor_tester.get_expected_values(a__ , batched=a__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __A ( self ): # prepare image and target _lowerCAmelCase : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: _lowerCAmelCase : Optional[Any] = json.loads(f.read() ) _lowerCAmelCase : Optional[int] = {"""image_id""": 39769, """annotations""": target} # encode them _lowerCAmelCase : Union[str, Any] = ConditionalDetrImageProcessor.from_pretrained("""microsoft/conditional-detr-resnet-50""" ) _lowerCAmelCase : Any = image_processing(images=a__ , annotations=a__ , return_tensors="""pt""" ) # verify pixel values _lowerCAmelCase : Union[str, Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , a__ ) _lowerCAmelCase : Optional[Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , a__ , atol=1e-4 ) ) # verify area _lowerCAmelCase : Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , a__ ) ) # verify boxes _lowerCAmelCase : str = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , a__ ) _lowerCAmelCase : Union[str, Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , a__ , atol=1e-3 ) ) # verify image_id _lowerCAmelCase : Any = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , a__ ) ) # verify is_crowd _lowerCAmelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , a__ ) ) # verify class_labels _lowerCAmelCase : str = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , a__ ) ) # verify orig_size _lowerCAmelCase : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , a__ ) ) # verify size _lowerCAmelCase : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , a__ ) ) @slow def __A ( self ): # prepare image, target and masks_path _lowerCAmelCase : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: _lowerCAmelCase : str = json.loads(f.read() ) _lowerCAmelCase : Dict = {"""file_name""": """000000039769.png""", """image_id""": 39769, """segments_info""": target} _lowerCAmelCase : Tuple = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them _lowerCAmelCase : List[str] = ConditionalDetrImageProcessor(format="""coco_panoptic""" ) _lowerCAmelCase : str = image_processing(images=a__ , annotations=a__ , masks_path=a__ , return_tensors="""pt""" ) # verify pixel values _lowerCAmelCase : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , a__ ) _lowerCAmelCase : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , a__ , atol=1e-4 ) ) # verify area _lowerCAmelCase : List[str] = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , a__ ) ) # verify boxes _lowerCAmelCase : Dict = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , a__ ) _lowerCAmelCase : Union[str, Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , a__ , atol=1e-3 ) ) # verify image_id _lowerCAmelCase : List[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , a__ ) ) # verify is_crowd _lowerCAmelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , a__ ) ) # verify class_labels _lowerCAmelCase : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , a__ ) ) # verify masks _lowerCAmelCase : int = 822873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , a__ ) # verify orig_size _lowerCAmelCase : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , a__ ) ) # verify size _lowerCAmelCase : Union[str, Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , a__ ) )
44
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
44
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> int: _lowerCAmelCase : Tuple = SwinvaConfig() _lowerCAmelCase : List[str] = swinva_name.split("""_""" ) _lowerCAmelCase : str = name_split[1] if "to" in name_split[3]: _lowerCAmelCase : Optional[int] = int(name_split[3][-3:] ) else: _lowerCAmelCase : Optional[Any] = int(name_split[3] ) if "to" in name_split[2]: _lowerCAmelCase : Optional[int] = int(name_split[2][-2:] ) else: _lowerCAmelCase : Tuple = int(name_split[2][6:] ) if model_size == "tiny": _lowerCAmelCase : Optional[Any] = 96 _lowerCAmelCase : Optional[int] = (2, 2, 6, 2) _lowerCAmelCase : Tuple = (3, 6, 12, 24) elif model_size == "small": _lowerCAmelCase : int = 96 _lowerCAmelCase : Tuple = (2, 2, 18, 2) _lowerCAmelCase : Optional[int] = (3, 6, 12, 24) elif model_size == "base": _lowerCAmelCase : List[Any] = 128 _lowerCAmelCase : Optional[int] = (2, 2, 18, 2) _lowerCAmelCase : Tuple = (4, 8, 16, 32) else: _lowerCAmelCase : Dict = 192 _lowerCAmelCase : Union[str, Any] = (2, 2, 18, 2) _lowerCAmelCase : str = (6, 12, 24, 48) if "to" in swinva_name: _lowerCAmelCase : Dict = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): _lowerCAmelCase : Optional[Any] = 21841 _lowerCAmelCase : str = """huggingface/label-files""" _lowerCAmelCase : str = """imagenet-22k-id2label.json""" _lowerCAmelCase : List[str] = json.load(open(hf_hub_download(_lowerCamelCase ,_lowerCamelCase ,repo_type="""dataset""" ) ,"""r""" ) ) _lowerCAmelCase : List[Any] = {int(_lowerCamelCase ): v for k, v in idalabel.items()} _lowerCAmelCase : int = idalabel _lowerCAmelCase : Tuple = {v: k for k, v in idalabel.items()} else: _lowerCAmelCase : Union[str, Any] = 1000 _lowerCAmelCase : List[Any] = """huggingface/label-files""" _lowerCAmelCase : Optional[int] = """imagenet-1k-id2label.json""" _lowerCAmelCase : Optional[Any] = json.load(open(hf_hub_download(_lowerCamelCase ,_lowerCamelCase ,repo_type="""dataset""" ) ,"""r""" ) ) _lowerCAmelCase : Tuple = {int(_lowerCamelCase ): v for k, v in idalabel.items()} _lowerCAmelCase : int = idalabel _lowerCAmelCase : List[str] = {v: k for k, v in idalabel.items()} _lowerCAmelCase : int = img_size _lowerCAmelCase : Optional[Any] = num_classes _lowerCAmelCase : List[str] = embed_dim _lowerCAmelCase : Any = depths _lowerCAmelCase : List[Any] = num_heads _lowerCAmelCase : Optional[Any] = window_size return config def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: if "patch_embed.proj" in name: _lowerCAmelCase : int = name.replace("""patch_embed.proj""" ,"""embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: _lowerCAmelCase : Any = name.replace("""patch_embed.norm""" ,"""embeddings.norm""" ) if "layers" in name: _lowerCAmelCase : Any = """encoder.""" + name if "attn.proj" in name: _lowerCAmelCase : int = name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name: _lowerCAmelCase : List[Any] = name.replace("""attn""" ,"""attention.self""" ) if "norm1" in name: _lowerCAmelCase : Union[str, Any] = name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: _lowerCAmelCase : Any = name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: _lowerCAmelCase : List[Any] = name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: _lowerCAmelCase : str = name.replace("""mlp.fc2""" ,"""output.dense""" ) if "q_bias" in name: _lowerCAmelCase : Union[str, Any] = name.replace("""q_bias""" ,"""query.bias""" ) if "k_bias" in name: _lowerCAmelCase : Any = name.replace("""k_bias""" ,"""key.bias""" ) if "v_bias" in name: _lowerCAmelCase : Dict = name.replace("""v_bias""" ,"""value.bias""" ) if "cpb_mlp" in name: _lowerCAmelCase : List[Any] = name.replace("""cpb_mlp""" ,"""continuous_position_bias_mlp""" ) if name == "norm.weight": _lowerCAmelCase : Optional[int] = """layernorm.weight""" if name == "norm.bias": _lowerCAmelCase : Optional[Any] = """layernorm.bias""" if "head" in name: _lowerCAmelCase : List[str] = name.replace("""head""" ,"""classifier""" ) else: _lowerCAmelCase : Optional[int] = """swinv2.""" + name return name def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int] ,_lowerCamelCase : List[Any] ) -> Union[str, Any]: for key in orig_state_dict.copy().keys(): _lowerCAmelCase : Any = orig_state_dict.pop(_lowerCamelCase ) if "mask" in key: continue elif "qkv" in key: _lowerCAmelCase : Union[str, Any] = key.split(""".""" ) _lowerCAmelCase : List[str] = int(key_split[1] ) _lowerCAmelCase : List[str] = int(key_split[3] ) _lowerCAmelCase : Union[str, Any] = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _lowerCAmelCase : Tuple = val[:dim, :] _lowerCAmelCase : Any = val[dim : dim * 2, :] _lowerCAmelCase : Any = val[-dim:, :] else: _lowerCAmelCase : Optional[int] = val[:dim] _lowerCAmelCase : int = val[ dim : dim * 2 ] _lowerCAmelCase : List[Any] = val[-dim:] else: _lowerCAmelCase : int = val return orig_state_dict def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : str = timm.create_model(_lowerCamelCase ,pretrained=_lowerCamelCase ) timm_model.eval() _lowerCAmelCase : Union[str, Any] = get_swinva_config(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = SwinvaForImageClassification(_lowerCamelCase ) model.eval() _lowerCAmelCase : List[str] = convert_state_dict(timm_model.state_dict() ,_lowerCamelCase ) model.load_state_dict(_lowerCamelCase ) _lowerCAmelCase : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" _lowerCAmelCase : Tuple = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" ,"""-""" ) ) ) _lowerCAmelCase : str = Image.open(requests.get(_lowerCamelCase ,stream=_lowerCamelCase ).raw ) _lowerCAmelCase : int = image_processor(images=_lowerCamelCase ,return_tensors="""pt""" ) _lowerCAmelCase : Optional[Any] = timm_model(inputs["""pixel_values"""] ) _lowerCAmelCase : Tuple = model(**_lowerCamelCase ).logits assert torch.allclose(_lowerCamelCase ,_lowerCamelCase ,atol=1e-3 ) print(f"Saving model {swinva_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCamelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_lowerCamelCase ) model.push_to_hub( repo_path_or_name=Path(_lowerCamelCase ,_lowerCamelCase ) ,organization="""nandwalritik""" ,commit_message="""Add model""" ,) if __name__ == "__main__": _a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swinv2_name', default='swinv2_tiny_patch4_window8_256', type=str, help='Name of the Swinv2 timm 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.' ) _a : Dict = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
44
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Dict = parent _lowerCAmelCase : str = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Dict = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Any = hidden_dropout_prob _lowerCAmelCase : List[str] = attention_probs_dropout_prob _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : Tuple = type_sequence_label_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Tuple = relative_attention _lowerCAmelCase : Tuple = position_biased_input _lowerCAmelCase : Dict = pos_att_type _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCAmelCase : str = None if self.use_token_type_ids: _lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return 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 , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self , a__ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] _lowerCAmelCase : List[Any] = model(a__ , token_type_ids=a__ )[0] _lowerCAmelCase : Any = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = DebertaVaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : int = self.num_labels _lowerCAmelCase : int = DebertaVaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = DebertaVaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = DebertaVaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _UpperCamelCase : str = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = True _UpperCamelCase : List[Any] = False _UpperCamelCase : List[Any] = False _UpperCamelCase : Dict = False _UpperCamelCase : Tuple = False def __A ( self ): _lowerCAmelCase : Optional[Any] = DebertaVaModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*a__ ) @slow def __A ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Tuple = DebertaVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def __A ( self ): pass @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) _lowerCAmelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _lowerCAmelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. _lowerCAmelCase : str = torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F"{output[:, 1:4, 1:4]}" )
44
1
"""simple docstring""" import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A : def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=3 , a__=0.6 , a__=None , ): _lowerCAmelCase : str = parent _lowerCAmelCase : int = batch_size _lowerCAmelCase : Optional[int] = image_size _lowerCAmelCase : Tuple = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Any = use_labels _lowerCAmelCase : str = hidden_size _lowerCAmelCase : Any = num_hidden_layers _lowerCAmelCase : int = num_attention_heads _lowerCAmelCase : Any = intermediate_size _lowerCAmelCase : Any = hidden_act _lowerCAmelCase : List[str] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : int = type_sequence_label_size _lowerCAmelCase : Tuple = initializer_range _lowerCAmelCase : Union[str, Any] = mask_ratio _lowerCAmelCase : Tuple = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) _lowerCAmelCase : List[str] = (image_size // patch_size) ** 2 _lowerCAmelCase : Any = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def __A ( self ): _lowerCAmelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : List[str] = None if self.use_labels: _lowerCAmelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = self.get_config() return config, pixel_values, labels def __A ( self ): return ViTMAEConfig( 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 , mask_ratio=self.mask_ratio , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : int = ViTMAEModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : int = ViTMAEForPreTraining(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Tuple = model(a__ ) _lowerCAmelCase : Dict = (self.image_size // self.patch_size) ** 2 _lowerCAmelCase : Tuple = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images _lowerCAmelCase : str = 1 _lowerCAmelCase : Dict = ViTMAEForPreTraining(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : List[Any] = model(a__ ) _lowerCAmelCase : List[str] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def __A ( self ): _lowerCAmelCase : Any = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Dict = config_and_inputs _lowerCAmelCase : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[str] = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () _UpperCamelCase : str = {"feature-extraction": ViTMAEModel} if is_torch_available() else {} _UpperCamelCase : Dict = False _UpperCamelCase : Optional[Any] = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : str = False def __A ( self ): _lowerCAmelCase : List[Any] = ViTMAEModelTester(self ) _lowerCAmelCase : List[str] = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Optional[Any] = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCAmelCase : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Optional[Any] = model_class(a__ ) _lowerCAmelCase : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : Union[str, Any] = [*signature.parameters.keys()] _lowerCAmelCase : Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def __A ( self ): _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a__ ) def __A ( self , a__ , a__ , a__ ): # make masks reproducible np.random.seed(2 ) _lowerCAmelCase : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) _lowerCAmelCase : int = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _lowerCAmelCase : str = torch.from_numpy(a__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument _lowerCAmelCase : Any = pt_noise super().check_pt_tf_models(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Union[str, Any] = model_class(a__ ) model.to(a__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): _lowerCAmelCase : List[str] = model(**self._prepare_for_class(a__ , a__ ) ) _lowerCAmelCase : Any = outputs[0].cpu().numpy() _lowerCAmelCase : Optional[Any] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a__ ) _lowerCAmelCase : Union[str, Any] = model_class.from_pretrained(a__ ) model.to(a__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): _lowerCAmelCase : List[Any] = model(**self._prepare_for_class(a__ , a__ ) ) # Make sure we don't have nans _lowerCAmelCase : Dict = after_outputs[0].cpu().numpy() _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def __A ( self ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def __A ( self ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def __A ( self ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def __A ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __A ( self ): pass @slow def __A ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Optional[Any] = ViTMAEModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def SCREAMING_SNAKE_CASE ( ) -> Tuple: _lowerCAmelCase : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def __A ( self ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def __A ( self ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) _lowerCAmelCase : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(a__ ) _lowerCAmelCase : Tuple = self.default_image_processor _lowerCAmelCase : Optional[int] = prepare_img() _lowerCAmelCase : Tuple = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) _lowerCAmelCase : str = ViTMAEConfig() _lowerCAmelCase : Any = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) _lowerCAmelCase : Union[str, Any] = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): _lowerCAmelCase : int = model(**a__ , noise=torch.from_numpy(a__ ).to(device=a__ ) ) # verify the logits _lowerCAmelCase : Dict = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , a__ ) _lowerCAmelCase : Optional[Any] = torch.tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(a__ ) , atol=1e-4 ) )
44
"""simple docstring""" import numpy as np import qiskit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 8 ,_lowerCamelCase : int | None = None ) -> str: _lowerCAmelCase : int = np.random.default_rng(seed=_lowerCamelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. _lowerCAmelCase : Dict = rng.integers(2 ,size=_lowerCamelCase ) # The set of states Alice will prepare. _lowerCAmelCase : Tuple = rng.integers(2 ,size=_lowerCamelCase ) # Measurement basis for Bob's qubits. _lowerCAmelCase : Union[str, Any] = rng.integers(2 ,size=_lowerCamelCase ) # Quantum Circuit to simulate BB84 _lowerCAmelCase : Dict = qiskit.QuantumCircuit(_lowerCamelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCamelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCAmelCase : int = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCAmelCase : List[str] = qiskit.execute(_lowerCamelCase ,_lowerCamelCase ,shots=1 ,seed_simulator=_lowerCamelCase ) # Returns the result of measurement. _lowerCAmelCase : List[Any] = job.result().get_counts(_lowerCamelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCAmelCase : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCAmelCase : List[Any] = gen_key[:key_len] if len(_lowerCamelCase ) >= key_len else gen_key.ljust(_lowerCamelCase ,"""0""" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list ,_lowerCamelCase : list ,_lowerCamelCase : int ) -> list: _lowerCAmelCase : List[str] = len(_lowerCamelCase ) _lowerCAmelCase : Dict = [[0] * n for i in range(_lowerCamelCase )] for i in range(_lowerCamelCase ): _lowerCAmelCase : int = y_points[i] for i in range(2 ,_lowerCamelCase ): for j in range(_lowerCamelCase ,_lowerCamelCase ): _lowerCAmelCase : Dict = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _a : Union[str, Any] = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _a : List[str] = 10 _a : List[Any] = 256 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[MinHash]: if len(_lowerCamelCase ) < MIN_NUM_TOKENS: return None _lowerCAmelCase : Optional[Any] = MinHash(num_perm=_lowerCamelCase ) for token in set(_lowerCamelCase ): min_hash.update(token.encode() ) return min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> Set[str]: return {t for t in NON_ALPHA.split(_lowerCamelCase ) if len(t.strip() ) > 0} class __A : def __init__( self , *, a__ = 0.8_5 , ): _lowerCAmelCase : List[Any] = duplication_jaccard_threshold _lowerCAmelCase : Union[str, Any] = NUM_PERM _lowerCAmelCase : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase : Optional[int] = defaultdict(a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[Any] = self._index.query(a__ ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(a__ , a__ ) if len(a__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(a__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(a__ ) def __A ( self ): _lowerCAmelCase : int = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase : List[str] = [base] + list(a__ ) # reformat the cluster to be a list of dict _lowerCAmelCase : List[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(a__ ) return duplicate_clusters def __A ( self , a__ ): _lowerCAmelCase : Dict = self.get_duplicate_clusters() with open(a__ , """w""" ) as f: json.dump(a__ , a__ ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : Tuple = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ) -> Optional[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash ,ThreadedIterator(_lowerCamelCase ,max_queue_size=10000 ) ,chunksize=100 ,): if data is not None: yield data def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float ) -> List[str]: _lowerCAmelCase : Optional[Any] = DuplicationIndex(duplication_jaccard_threshold=_lowerCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_lowerCamelCase ) ) ,max_queue_size=100 ) ): di.add(_lowerCamelCase ,_lowerCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> float: _lowerCAmelCase : Any = get_tokens(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = get_tokens(_lowerCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _a : str = None def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : List[Any] ) -> Dict: _lowerCAmelCase : int = [] for elementa in cluster: _lowerCAmelCase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: _lowerCAmelCase : Any = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(_lowerCamelCase ,_lowerCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase : Any = 1 extremes.append(_lowerCamelCase ) return extremes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Any ) -> str: global _shared_dataset _lowerCAmelCase : Tuple = dataset _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Optional[Any] = partial(_find_cluster_extremes_shared ,jaccard_threshold=_lowerCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _lowerCamelCase ,_lowerCamelCase ,) ,total=len(_lowerCamelCase ) ,): extremes_list.append(_lowerCamelCase ) return extremes_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase : Tuple = make_duplicate_clusters(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase : Optional[int] = {} _lowerCAmelCase : Tuple = find_extremes(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : List[Any] = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase : List[Any] = dataset.filter(lambda _lowerCamelCase ,_lowerCamelCase : idx not in remove_indices ,with_indices=_lowerCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase : Tuple = element["""base_index"""] in extreme_dict if element["is_extreme"]: _lowerCAmelCase : Dict = extreme_dict[element["""base_index"""]]["""copies"""] print(f"Original dataset size: {len(_lowerCamelCase )}" ) print(f"Number of duplicate clusters: {len(_lowerCamelCase )}" ) print(f"Files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Filtered dataset size: {len(_lowerCamelCase )}" ) return ds_filter, duplicate_clusters
44
1
"""simple docstring""" import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer 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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class __A : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=4 , a__="gelu" , a__=0.0 , a__=0.1 , a__=True , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Optional[int] = parent _lowerCAmelCase : List[str] = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Optional[int] = is_training _lowerCAmelCase : List[str] = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : str = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : List[str] = hidden_size _lowerCAmelCase : Optional[int] = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_multiple_size _lowerCAmelCase : Dict = hidden_act _lowerCAmelCase : List[str] = hidden_dropout _lowerCAmelCase : Dict = attention_dropout _lowerCAmelCase : List[str] = weight_tying _lowerCAmelCase : str = max_position_embeddings _lowerCAmelCase : Optional[Any] = type_vocab_size _lowerCAmelCase : str = type_sequence_label_size _lowerCAmelCase : Optional[int] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : Any = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase : Union[str, Any] = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : int = self.get_config() return config, input_ids, input_mask, token_labels def __A ( self ): return GPTNeoXJapaneseConfig( 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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a__ , initializer_range=self.initializer_range , ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() _lowerCAmelCase : Dict = True return config, input_ids, input_mask, token_labels def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = GPTNeoXJapaneseModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = model(a__ , attention_mask=a__ ) _lowerCAmelCase : Optional[Any] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = True _lowerCAmelCase : Optional[int] = GPTNeoXJapaneseModel(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = GPTNeoXJapaneseForCausalLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Any = True _lowerCAmelCase : str = GPTNeoXJapaneseForCausalLM(config=a__ ) model.to(a__ ) model.eval() # first forward pass _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , use_cache=a__ ) _lowerCAmelCase : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCAmelCase : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _lowerCAmelCase : Optional[int] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _lowerCAmelCase : str = torch.cat([input_ids, next_tokens] , dim=-1 ) _lowerCAmelCase : List[Any] = torch.cat([input_mask, next_mask] , dim=-1 ) _lowerCAmelCase : List[str] = model(a__ , attention_mask=a__ , output_hidden_states=a__ ) _lowerCAmelCase : Union[str, Any] = output_from_no_past["""hidden_states"""][0] _lowerCAmelCase : int = model( a__ , attention_mask=a__ , past_key_values=a__ , output_hidden_states=a__ , )["""hidden_states"""][0] # select random slice _lowerCAmelCase : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() _lowerCAmelCase : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCAmelCase : Optional[int] = 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 __A ( self ): _lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Any = config_and_inputs _lowerCAmelCase : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () _UpperCamelCase : int = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () _UpperCamelCase : str = ( {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) _UpperCamelCase : List[str] = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : str = False _UpperCamelCase : int = False def __A ( self ): _lowerCAmelCase : Optional[Any] = GPTNeoXJapaneseModelTester(self ) _lowerCAmelCase : Union[str, Any] = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(a__ , a__ , a__ ) def __A ( self ): # This regression test was failing with PyTorch < 1.3 _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() _lowerCAmelCase : Tuple = None self.model_tester.create_and_check_model_as_decoder(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*a__ ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = """abeja/gpt-neox-japanese-2.7b""" _lowerCAmelCase : Optional[Any] = ["""データサイエンティストとは、""", """100年後に必要とされる会社は、""", """フルリモートの環境で働くために必要なことは、""", """国境の長いトンネルを抜けると""", """美味しい日本食といえば、"""] _lowerCAmelCase : Optional[int] = [ """データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。""", """100年後に必要とされる会社は、「人」が中心の会社です。""", """フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。""", """国境の長いトンネルを抜けると、そこは雪国だった。""", """美味しい日本食といえば、やっぱりお寿司ですよね。""", ] _lowerCAmelCase : Tuple = GPTNeoXJapaneseTokenizer.from_pretrained(a__ ) _lowerCAmelCase : int = GPTNeoXJapaneseForCausalLM.from_pretrained(a__ ) _lowerCAmelCase : List[str] = [] for prompt in prompts: _lowerCAmelCase : str = tokenizer(a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : int = model.generate(a__ , max_length=50 ) _lowerCAmelCase : Dict = tokenizer.batch_decode(a__ , skip_special_tokens=a__ ) predicted_outputs += generated_string self.assertListEqual(a__ , a__ )
44
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
1
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig _a : List[Any] = logging.get_logger(__name__) # General docstring _a : Optional[int] = 'RegNetConfig' # Base docstring _a : Union[str, Any] = 'facebook/regnet-y-040' _a : Tuple = [1, 1_088, 7, 7] # Image classification docstring _a : Tuple = 'facebook/regnet-y-040' _a : Union[str, Any] = 'tabby, tabby cat' _a : Union[str, Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 3 , a__ = 1 , a__ = 1 , a__ = "relu" , ): super().__init__() _lowerCAmelCase : str = nn.Convad( a__ , a__ , kernel_size=a__ , stride=a__ , padding=kernel_size // 2 , groups=a__ , bias=a__ , ) _lowerCAmelCase : str = nn.BatchNormad(a__ ) _lowerCAmelCase : Optional[int] = ACTaFN[activation] if activation is not None else nn.Identity() def __A ( self , a__ ): _lowerCAmelCase : List[str] = self.convolution(a__ ) _lowerCAmelCase : Union[str, Any] = self.normalization(a__ ) _lowerCAmelCase : List[Any] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) _lowerCAmelCase : List[Any] = config.num_channels def __A ( self , a__ ): _lowerCAmelCase : Tuple = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) _lowerCAmelCase : List[Any] = self.embedder(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 2 ): super().__init__() _lowerCAmelCase : Union[str, Any] = nn.Convad(a__ , a__ , kernel_size=1 , stride=a__ , bias=a__ ) _lowerCAmelCase : Optional[int] = nn.BatchNormad(a__ ) def __A ( self , a__ ): _lowerCAmelCase : str = self.convolution(a__ ) _lowerCAmelCase : Tuple = self.normalization(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ ): super().__init__() _lowerCAmelCase : Dict = nn.AdaptiveAvgPoolad((1, 1) ) _lowerCAmelCase : Tuple = nn.Sequential( nn.Convad(a__ , a__ , kernel_size=1 ) , nn.ReLU() , nn.Convad(a__ , a__ , kernel_size=1 ) , nn.Sigmoid() , ) def __A ( self , a__ ): # b c h w -> b c 1 1 _lowerCAmelCase : Tuple = self.pooler(a__ ) _lowerCAmelCase : int = self.attention(a__ ) _lowerCAmelCase : Optional[Any] = hidden_state * attention return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Optional[Any] = in_channels != out_channels or stride != 1 _lowerCAmelCase : Optional[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : Tuple = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : str = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Union[str, Any] = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : Any = hidden_state _lowerCAmelCase : Any = self.layer(a__ ) _lowerCAmelCase : str = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : int = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Dict = in_channels != out_channels or stride != 1 _lowerCAmelCase : List[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : List[Any] = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : Tuple = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetSELayer(a__ , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Dict = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : List[str] = hidden_state _lowerCAmelCase : Optional[int] = self.layer(a__ ) _lowerCAmelCase : List[Any] = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : List[str] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 2 , a__ = 2 , ): super().__init__() _lowerCAmelCase : List[Any] = RegNetXLayer if config.layer_type == """x""" else RegNetYLayer _lowerCAmelCase : str = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( a__ , a__ , a__ , stride=a__ , ) , *[layer(a__ , a__ , a__ ) for _ in range(depth - 1 )] , ) def __A ( self , a__ ): _lowerCAmelCase : List[Any] = self.layers(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( a__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) _lowerCAmelCase : List[str] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(a__ , config.depths[1:] ): self.stages.append(RegNetStage(a__ , a__ , a__ , depth=a__ ) ) def __A ( self , a__ , a__ = False , a__ = True ): _lowerCAmelCase : Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _lowerCAmelCase : Union[str, Any] = hidden_states + (hidden_state,) _lowerCAmelCase : Union[str, Any] = stage_module(a__ ) if output_hidden_states: _lowerCAmelCase : Union[str, Any] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=a__ , hidden_states=a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = RegNetConfig _UpperCamelCase : int = "regnet" _UpperCamelCase : List[str] = "pixel_values" _UpperCamelCase : Union[str, Any] = True def __A ( self , a__ ): if isinstance(a__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __A ( self , a__ , a__=False ): if isinstance(a__ , a__ ): _lowerCAmelCase : Optional[int] = value _a : List[Any] = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _a : List[Any] = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[Any] = config _lowerCAmelCase : Any = RegNetEmbeddings(a__ ) _lowerCAmelCase : List[str] = RegNetEncoder(a__ ) _lowerCAmelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self , a__ , a__ = None , a__ = None ): _lowerCAmelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : List[Any] = self.embedder(a__ ) _lowerCAmelCase : Optional[Any] = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = encoder_outputs[0] _lowerCAmelCase : Optional[Any] = self.pooler(a__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a__ , pooler_output=a__ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config.num_labels _lowerCAmelCase : Optional[int] = RegNetModel(a__ ) # classification head _lowerCAmelCase : Optional[Any] = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self , a__ = None , a__ = None , a__ = None , a__ = None , ): _lowerCAmelCase : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : Union[str, Any] = self.regnet(a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = outputs.pooler_output if return_dict else outputs[1] _lowerCAmelCase : str = self.classifier(a__ ) _lowerCAmelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _lowerCAmelCase : str = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _lowerCAmelCase : Optional[int] = """single_label_classification""" else: _lowerCAmelCase : Optional[int] = """multi_label_classification""" if self.config.problem_type == "regression": _lowerCAmelCase : Optional[Any] = MSELoss() if self.num_labels == 1: _lowerCAmelCase : int = loss_fct(logits.squeeze() , labels.squeeze() ) else: _lowerCAmelCase : Dict = loss_fct(a__ , a__ ) elif self.config.problem_type == "single_label_classification": _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _lowerCAmelCase : Dict = BCEWithLogitsLoss() _lowerCAmelCase : Tuple = loss_fct(a__ , a__ ) if not return_dict: _lowerCAmelCase : Optional[int] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states )
44
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : List[Any] = torch.exp(_lowerCamelCase ) _lowerCAmelCase : List[Any] = torch.sum(_lowerCamelCase ,dim=1 ) # sum of exp(x_i) _lowerCAmelCase : Dict = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : int = config.output_attentions _lowerCAmelCase : Any = config.output_hidden_states _lowerCAmelCase : List[Any] = nn.ModuleList([BertLayer(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : Any = nn.ModuleList([BertHighway(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : str = [-1 for _ in range(config.num_hidden_layers )] def __A ( self , a__ ): if (type(a__ ) is float) or (type(a__ ) is int): for i in range(len(self.early_exit_entropy ) ): _lowerCAmelCase : Tuple = x else: _lowerCAmelCase : Optional[int] = x def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __A ( self , a__ , a__=None , a__=None , a__=None , a__=None , ): _lowerCAmelCase : Any = () _lowerCAmelCase : Optional[int] = () _lowerCAmelCase : List[Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _lowerCAmelCase : str = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[str] = layer_module( a__ , a__ , head_mask[i] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = layer_outputs[0] if self.output_attentions: _lowerCAmelCase : Dict = all_attentions + (layer_outputs[1],) _lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Optional[int] = current_outputs + (all_attentions,) _lowerCAmelCase : Optional[Any] = self.highway[i](a__ ) # logits, pooled_output if not self.training: _lowerCAmelCase : Tuple = highway_exit[0] _lowerCAmelCase : Any = entropy(a__ ) _lowerCAmelCase : Optional[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _lowerCAmelCase : Union[str, Any] = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _lowerCAmelCase : List[str] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a__ , i + 1 ) else: _lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _lowerCAmelCase : List[Any] = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[Any] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : List[str] = outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Any = outputs + (all_attentions,) _lowerCAmelCase : Optional[int] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config _lowerCAmelCase : Tuple = BertEmbeddings(a__ ) _lowerCAmelCase : Tuple = DeeBertEncoder(a__ ) _lowerCAmelCase : List[str] = BertPooler(a__ ) self.init_weights() def __A ( self ): self.encoder.init_highway_pooler(self.pooler ) def __A ( self ): return self.embeddings.word_embeddings def __A ( self , a__ ): _lowerCAmelCase : Dict = value def __A ( self , a__ ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a__ ) @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _lowerCAmelCase : Any = input_ids.size() elif inputs_embeds is not None: _lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _lowerCAmelCase : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _lowerCAmelCase : List[Any] = torch.ones(a__ , device=a__ ) if encoder_attention_mask is None: _lowerCAmelCase : Optional[Any] = torch.ones(a__ , device=a__ ) if token_type_ids is None: _lowerCAmelCase : Dict = torch.zeros(a__ , dtype=torch.long , device=a__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(a__ , a__ , a__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _lowerCAmelCase : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _lowerCAmelCase : Tuple = encoder_attention_mask[:, None, None, :] _lowerCAmelCase : Union[str, Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _lowerCAmelCase : Optional[Any] = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _lowerCAmelCase : Optional[int] = self.get_head_mask(a__ , self.config.num_hidden_layers ) _lowerCAmelCase : Dict = self.embeddings( input_ids=a__ , position_ids=a__ , token_type_ids=a__ , inputs_embeds=a__ ) _lowerCAmelCase : Union[str, Any] = self.encoder( a__ , attention_mask=a__ , head_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Dict = encoder_outputs[0] _lowerCAmelCase : Union[str, Any] = self.pooler(a__ ) _lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ ): _lowerCAmelCase : str = message _lowerCAmelCase : str = exit_layer # start from 1! class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Any = BertPooler(a__ ) _lowerCAmelCase : str = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def __A ( self , a__ ): # Pooler _lowerCAmelCase : Tuple = encoder_outputs[0] _lowerCAmelCase : int = self.pooler(a__ ) # "return" pooler_output # BertModel _lowerCAmelCase : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _lowerCAmelCase : Optional[int] = bmodel_output[1] _lowerCAmelCase : Tuple = self.dropout(a__ ) _lowerCAmelCase : Dict = self.classifier(a__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[str] = config.num_labels _lowerCAmelCase : Optional[Any] = config.num_hidden_layers _lowerCAmelCase : str = DeeBertModel(a__ ) _lowerCAmelCase : Tuple = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : List[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=-1 , a__=False , ): _lowerCAmelCase : Dict = self.num_layers try: _lowerCAmelCase : str = self.bert( a__ , attention_mask=a__ , token_type_ids=a__ , position_ids=a__ , head_mask=a__ , inputs_embeds=a__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _lowerCAmelCase : Any = outputs[1] _lowerCAmelCase : Optional[int] = self.dropout(a__ ) _lowerCAmelCase : List[str] = self.classifier(a__ ) _lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : int = e.exit_layer _lowerCAmelCase : Union[str, Any] = outputs[0] if not self.training: _lowerCAmelCase : Tuple = entropy(a__ ) _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Tuple = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase : Optional[Any] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Dict = highway_exit[0] if not self.training: highway_logits_all.append(a__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Optional[int] = CrossEntropyLoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(a__ ) if train_highway: _lowerCAmelCase : List[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Dict = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Dict = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
1
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _a : Any = 'pt' elif is_tf_available(): _a : List[Any] = 'tf' else: _a : str = 'jax' class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = PerceiverTokenizer _UpperCamelCase : Optional[int] = False def __A ( self ): super().setUp() _lowerCAmelCase : Union[str, Any] = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __A ( self ): return PerceiverTokenizer.from_pretrained("""deepmind/language-perceiver""" ) def __A ( self , **a__ ): return self.tokenizer_class.from_pretrained(self.tmpdirname , **a__ ) def __A ( self , a__ , a__=False , a__=20 , a__=5 ): # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. _lowerCAmelCase : List[str] = [] for i in range(len(a__ ) ): try: _lowerCAmelCase : int = tokenizer.decode([i] , clean_up_tokenization_spaces=a__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) _lowerCAmelCase : int = list(filter(lambda a__ : re.match(r"""^[ a-zA-Z]+$""" , t[1] ) , a__ ) ) _lowerCAmelCase : Union[str, Any] = list(filter(lambda a__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=a__ ) , a__ ) ) if max_length is not None and len(a__ ) > max_length: _lowerCAmelCase : Optional[int] = toks[:max_length] if min_length is not None and len(a__ ) < min_length and len(a__ ) > 0: while len(a__ ) < min_length: _lowerCAmelCase : Dict = toks + toks # toks_str = [t[1] for t in toks] _lowerCAmelCase : Union[str, Any] = [t[0] for t in toks] # Ensure consistency _lowerCAmelCase : Tuple = tokenizer.decode(a__ , clean_up_tokenization_spaces=a__ ) if " " not in output_txt and len(a__ ) > 1: _lowerCAmelCase : Dict = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=a__ ) + """ """ + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=a__ ) ) if with_prefix_space: _lowerCAmelCase : Tuple = """ """ + output_txt _lowerCAmelCase : Optional[Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) return output_txt, output_ids def __A ( self ): _lowerCAmelCase : int = self.perceiver_tokenizer _lowerCAmelCase : Optional[int] = """Unicode €.""" _lowerCAmelCase : Union[str, Any] = tokenizer(a__ ) _lowerCAmelCase : List[Any] = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded["""input_ids"""] , a__ ) # decoding _lowerCAmelCase : Union[str, Any] = tokenizer.decode(a__ ) self.assertEqual(a__ , """[CLS]Unicode €.[SEP]""" ) _lowerCAmelCase : Dict = tokenizer("""e è é ê ë""" ) _lowerCAmelCase : int = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded["""input_ids"""] , a__ ) # decoding _lowerCAmelCase : List[str] = tokenizer.decode(a__ ) self.assertEqual(a__ , """[CLS]e è é ê ë[SEP]""" ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë""" ) ) , """[CLS]e è é ê ë[SEP]""" ) def __A ( self ): _lowerCAmelCase : str = self.perceiver_tokenizer _lowerCAmelCase : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] # fmt: off _lowerCAmelCase : Any = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on _lowerCAmelCase : List[str] = tokenizer(a__ , padding=a__ , return_tensors=a__ ) self.assertIsInstance(a__ , a__ ) if FRAMEWORK != "jax": _lowerCAmelCase : str = list(batch.input_ids.numpy()[0] ) else: _lowerCAmelCase : List[Any] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(a__ , a__ ) self.assertEqual((2, 38) , batch.input_ids.shape ) self.assertEqual((2, 38) , batch.attention_mask.shape ) def __A ( self ): _lowerCAmelCase : Optional[Any] = self.perceiver_tokenizer _lowerCAmelCase : str = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] _lowerCAmelCase : Optional[Any] = tokenizer(a__ , padding=a__ , return_tensors=a__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn("""input_ids""" , a__ ) self.assertIn("""attention_mask""" , a__ ) self.assertNotIn("""decoder_input_ids""" , a__ ) self.assertNotIn("""decoder_attention_mask""" , a__ ) def __A ( self ): _lowerCAmelCase : Dict = self.perceiver_tokenizer _lowerCAmelCase : int = [ """Summary of the text.""", """Another summary.""", ] _lowerCAmelCase : Optional[int] = tokenizer( text_target=a__ , max_length=32 , padding="""max_length""" , truncation=a__ , return_tensors=a__ ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def __A ( self ): # safety check on max_len default value so we are sure the test works _lowerCAmelCase : List[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test _lowerCAmelCase : Union[str, Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc _lowerCAmelCase : Optional[int] = tempfile.mkdtemp() _lowerCAmelCase : Dict = """ He is very happy, UNwant\u00E9d,running""" _lowerCAmelCase : Optional[int] = tokenizer.encode(a__ , add_special_tokens=a__ ) tokenizer.save_pretrained(a__ ) _lowerCAmelCase : Dict = tokenizer.__class__.from_pretrained(a__ ) _lowerCAmelCase : Optional[int] = after_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) shutil.rmtree(a__ ) _lowerCAmelCase : Tuple = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : List[str] = """ He is very happy, UNwant\u00E9d,running""" tokenizer.add_tokens(["""bim""", """bambam"""] ) _lowerCAmelCase : Optional[Any] = tokenizer.additional_special_tokens additional_special_tokens.append("""new_additional_special_token""" ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) _lowerCAmelCase : Optional[Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) tokenizer.save_pretrained(a__ ) _lowerCAmelCase : Tuple = tokenizer.__class__.from_pretrained(a__ ) _lowerCAmelCase : Optional[int] = after_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) self.assertIn("""new_additional_special_token""" , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) _lowerCAmelCase : Dict = tokenizer.__class__.from_pretrained(a__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(a__ ) def __A ( self ): _lowerCAmelCase : Dict = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a__ ) with open(os.path.join(a__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: _lowerCAmelCase : Any = json.load(a__ ) with open(os.path.join(a__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: _lowerCAmelCase : Union[str, Any] = json.load(a__ ) _lowerCAmelCase : int = [F"<extra_id_{i}>" for i in range(125 )] _lowerCAmelCase : int = added_tokens_extra_ids + [ """an_additional_special_token""" ] _lowerCAmelCase : Any = added_tokens_extra_ids + [ """an_additional_special_token""" ] with open(os.path.join(a__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(a__ , a__ ) with open(os.path.join(a__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(a__ , a__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _lowerCAmelCase : List[str] = tokenizer_class.from_pretrained( a__ , ) self.assertIn( """an_additional_special_token""" , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ["""an_additional_special_token"""] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _lowerCAmelCase : List[Any] = added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token""" , lstrip=a__ )] _lowerCAmelCase : List[Any] = tokenizer_class.from_pretrained( a__ , additional_special_tokens=a__ , ) self.assertIn("""a_new_additional_special_token""" , tokenizer.additional_special_tokens ) self.assertEqual( ["""a_new_additional_special_token"""] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""] ) ) , ) def __A ( self ): _lowerCAmelCase : List[str] = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178] ) , """�""" ) def __A ( self ): pass def __A ( self ): pass def __A ( self ): pass def __A ( self ): pass def __A ( self ): # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens _lowerCAmelCase : int = self.get_tokenizers(fast=a__ , do_lower_case=a__ ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): _lowerCAmelCase : List[str] = ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""] _lowerCAmelCase : Union[str, Any] = tokenizer.convert_tokens_to_string(a__ ) self.assertIsInstance(a__ , a__ )
44
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : str = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , a__ = None , a__ = None , **a__ , ): super().__init__(self , **a__ ) _lowerCAmelCase : Any = repo_info _lowerCAmelCase : Optional[Any] = token _lowerCAmelCase : Optional[int] = None def __A ( self ): if self.dir_cache is None: _lowerCAmelCase : Optional[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowerCAmelCase : 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 __A ( self , a__ , a__ = "rb" , **a__ , ): if not isinstance(self.repo_info , a__ ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) _lowerCAmelCase : Tuple = 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 __A ( self , a__ , **a__ ): self._get_dirs() _lowerCAmelCase : Union[str, Any] = self._strip_protocol(a__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a__ ) def __A ( self , a__ , a__=False , **a__ ): self._get_dirs() _lowerCAmelCase : Any = PurePosixPath(path.strip("""/""" ) ) _lowerCAmelCase : List[str] = {} for p, f in self.dir_cache.items(): _lowerCAmelCase : Any = PurePosixPath(p.strip("""/""" ) ) _lowerCAmelCase : Optional[int] = p.parent if root == path: _lowerCAmelCase : Dict = f _lowerCAmelCase : Union[str, Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
44
1
"""simple docstring""" import unittest from transformers import MPNetConfig, 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 ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class __A : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=False , a__=True , a__=99 , a__=64 , a__=5 , a__=4 , a__=64 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Optional[int] = parent _lowerCAmelCase : Optional[Any] = batch_size _lowerCAmelCase : Optional[int] = seq_length _lowerCAmelCase : str = is_training _lowerCAmelCase : List[str] = use_input_mask _lowerCAmelCase : Union[str, Any] = use_token_type_ids _lowerCAmelCase : Any = use_labels _lowerCAmelCase : Any = vocab_size _lowerCAmelCase : str = hidden_size _lowerCAmelCase : str = num_hidden_layers _lowerCAmelCase : Union[str, Any] = num_attention_heads _lowerCAmelCase : Optional[int] = intermediate_size _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : int = hidden_dropout_prob _lowerCAmelCase : List[Any] = attention_probs_dropout_prob _lowerCAmelCase : str = max_position_embeddings _lowerCAmelCase : int = type_vocab_size _lowerCAmelCase : Any = type_sequence_label_size _lowerCAmelCase : List[str] = initializer_range _lowerCAmelCase : List[Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Optional[Any] = scope def __A ( self ): return MPNetConfig.from_pretrained("""microsoft/mpnet-base""" ) def __A ( self ): _lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Dict = None if self.use_input_mask: _lowerCAmelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase : Optional[Any] = None _lowerCAmelCase : Optional[Any] = None _lowerCAmelCase : List[Any] = None if self.use_labels: _lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : int = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = MPNetModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Union[str, Any] = model(a__ , a__ ) _lowerCAmelCase : int = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Optional[int] = MPNetForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : str = model( a__ , attention_mask=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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Optional[int] = self.num_labels _lowerCAmelCase : Union[str, Any] = MPNetForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = self.num_choices _lowerCAmelCase : Tuple = MPNetForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = model( a__ , attention_mask=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = self.num_labels _lowerCAmelCase : List[str] = MPNetForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ((_lowerCAmelCase) , (_lowerCAmelCase) , (_lowerCAmelCase) , (_lowerCAmelCase) , (_lowerCAmelCase) , (_lowerCAmelCase)) : int = config_and_inputs _lowerCAmelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) _UpperCamelCase : Optional[int] = ( { "feature-extraction": MPNetModel, "fill-mask": MPNetForMaskedLM, "question-answering": MPNetForQuestionAnswering, "text-classification": MPNetForSequenceClassification, "token-classification": MPNetForTokenClassification, "zero-shot": MPNetForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Dict = False _UpperCamelCase : List[str] = True def __A ( self ): _lowerCAmelCase : int = MPNetModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*a__ ) def __A ( self ): _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*a__ ) @require_torch class __A ( unittest.TestCase ): @slow def __A ( self ): _lowerCAmelCase : Optional[Any] = MPNetModel.from_pretrained("""microsoft/mpnet-base""" ) _lowerCAmelCase : str = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) _lowerCAmelCase : Optional[int] = model(a__ )[0] _lowerCAmelCase : List[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a__ ) _lowerCAmelCase : str = torch.tensor( [[[-0.0_5_5_0, 0.1_9_4_3, -0.0_7_4_0], [-0.0_5_6_2, 0.2_2_1_1, -0.0_5_7_9], [-0.0_4_3_7, 0.3_3_3_7, -0.0_6_4_1]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , a__ , atol=1e-4 ) )
44
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_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""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): 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 __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Union[str, Any] = logging.get_logger(__name__) _a : str = { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json', 'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json', 'cl-tohoku/bert-base-japanese-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json' ), 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json', # See all BERT models at https://huggingface.co/models?filter=bert } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[int] = "bert" def __init__( self , a__=30522 , a__=768 , a__=12 , a__=12 , a__=3072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=2 , a__=0.0_2 , a__=1e-12 , a__=0 , a__="absolute" , a__=True , a__=None , **a__ , ): super().__init__(pad_token_id=a__ , **a__ ) _lowerCAmelCase : Optional[Any] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Union[str, Any] = num_hidden_layers _lowerCAmelCase : Union[str, Any] = num_attention_heads _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Dict = intermediate_size _lowerCAmelCase : Union[str, Any] = hidden_dropout_prob _lowerCAmelCase : Dict = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : int = initializer_range _lowerCAmelCase : List[str] = layer_norm_eps _lowerCAmelCase : Union[str, Any] = position_embedding_type _lowerCAmelCase : str = use_cache _lowerCAmelCase : Union[str, Any] = classifier_dropout class __A ( SCREAMING_SNAKE_CASE_ ): @property def __A ( self ): if self.task == "multiple-choice": _lowerCAmelCase : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCAmelCase : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
44
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 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(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
1
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
0
"""simple docstring""" _a : List[str] = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.13.2', 'requests-mock': 'requests-mock==1.10.0', 'importlib_metadata': 'importlib_metadata', 'invisible-watermark': 'invisible-watermark', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2', 'jaxlib': 'jaxlib>=0.1.65', 'Jinja2': 'Jinja2', 'k-diffusion': 'k-diffusion>=0.0.12', 'torchsde': 'torchsde', 'note_seq': 'note_seq', 'librosa': 'librosa', 'numpy': 'numpy', 'omegaconf': 'omegaconf', 'parameterized': 'parameterized', 'protobuf': 'protobuf>=3.20.3,<4', 'pytest': 'pytest', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'ruff': 'ruff>=0.0.241', 'safetensors': 'safetensors', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'scipy': 'scipy', 'onnx': 'onnx', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'tensorboard': 'tensorboard', 'torch': 'torch>=1.4', 'torchvision': 'torchvision', 'transformers': 'transformers>=4.25.1', 'urllib3': 'urllib3<=2.0.0', }
44
0
'''simple docstring''' from __future__ import annotations SCREAMING_SNAKE_CASE_: Tuple =1.6_0_2_1E-1_9 # units = C def lowerCAmelCase_ ( snake_case_ : float , snake_case_ : float , snake_case_ : float , ) -> tuple[str, float]: '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
1
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _a : Dict = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , *a__ , **a__ ): super().__init__(*a__ , **a__ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , a__=None , a__=None , a__=None ): _lowerCAmelCase : List[str] = {} _lowerCAmelCase : Union[str, Any] = {} if prompt is not None: _lowerCAmelCase : List[Any] = prompt if generate_kwargs is not None: _lowerCAmelCase : List[str] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _lowerCAmelCase : str = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) _lowerCAmelCase : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , a__ , **a__ ): return super().__call__(a__ , **a__ ) def __A ( self , a__ , a__=None ): _lowerCAmelCase : Tuple = load_image(a__ ) if prompt is not None: if not isinstance(a__ , a__ ): raise ValueError( F"Received an invalid text input, got - {type(a__ )} - but expected a single string. " """Note also that one single text can be provided for conditional image to text generation.""" ) _lowerCAmelCase : Optional[int] = self.model.config.model_type if model_type == "git": _lowerCAmelCase : Optional[Any] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : List[str] = self.tokenizer(text=a__ , add_special_tokens=a__ ).input_ids _lowerCAmelCase : Union[str, Any] = [self.tokenizer.cls_token_id] + input_ids _lowerCAmelCase : Dict = torch.tensor(a__ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _lowerCAmelCase : Tuple = self.image_processor(images=a__ , header_text=a__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _lowerCAmelCase : Optional[int] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : Optional[int] = self.tokenizer(a__ , return_tensors=self.framework ) model_inputs.update(a__ ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: _lowerCAmelCase : Any = self.image_processor(images=a__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _lowerCAmelCase : Union[str, Any] = None return model_inputs def __A ( self , a__ , a__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , a__ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _lowerCAmelCase : Optional[int] = None if generate_kwargs is None: _lowerCAmelCase : List[str] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _lowerCAmelCase : Tuple = model_inputs.pop(self.model.main_input_name ) _lowerCAmelCase : Union[str, Any] = self.model.generate(a__ , **a__ , **a__ ) return model_outputs def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for output_ids in model_outputs: _lowerCAmelCase : Any = { """generated_text""": self.tokenizer.decode( a__ , skip_special_tokens=a__ , ) } records.append(a__ ) return records
44
0
'''simple docstring''' from ....utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : int=2048 ): '''simple docstring''' lowercase__ = config.__dict__ lowercase__ = modal_hidden_size if num_labels: lowercase__ = num_labels
2
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _a : Dict = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.BuilderConfig ): _UpperCamelCase : int = 10_000 _UpperCamelCase : Optional[List[str]] = None _UpperCamelCase : Optional[datasets.Features] = None class __A ( datasets.ArrowBasedBuilder ): _UpperCamelCase : List[str] = ParquetConfig def __A ( self ): return datasets.DatasetInfo(features=self.config.features ) def __A ( self , a__ ): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) _lowerCAmelCase : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): _lowerCAmelCase : Any = data_files if isinstance(a__ , a__ ): _lowerCAmelCase : Tuple = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Any = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] _lowerCAmelCase : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): _lowerCAmelCase : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _lowerCAmelCase : Tuple = [dl_manager.iter_files(a__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(a__ ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(a__ ) ) break splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , a__ ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _lowerCAmelCase : Optional[int] = table_cast(a__ , self.info.features.arrow_schema ) return pa_table def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ): with open(a__ , """rb""" ) as f: _lowerCAmelCase : Tuple = pq.ParquetFile(a__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): _lowerCAmelCase : Any = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(a__ ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
44
0
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = IFPipeline __magic_name__ = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} __magic_name__ = TEXT_TO_IMAGE_BATCH_PARAMS __magic_name__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return self._get_dummy_components() def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> Optional[int]: """simple docstring""" if str(SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A : str = torch.manual_seed(SCREAMING_SNAKE_CASE ) else: A : List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) A : Any = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" self._test_save_load_local() def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[int] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) A : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) A, A : Optional[Any] = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() A : List[Any] = None A : List[Any] = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img A : Optional[Any] = IFImgaImgPipeline(**pipe_a.components ) A : Union[str, Any] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting A : str = IFInpaintingPipeline(**pipe_a.components ) A : Any = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _start_torch_memory_measurement() A : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : Dict = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE , output_type='''np''' , ) A : Any = output.images[0] assert image.shape == (64, 64, 3) A : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 A : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() A : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : List[str] = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) A : List[str] = output.images[0] assert image.shape == (256, 256, 3) A : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 A : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _start_torch_memory_measurement() A : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : Any = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE , output_type='''np''' , ) A : List[str] = output.images[0] assert image.shape == (64, 64, 3) A : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 A : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() A : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : Union[str, Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : Tuple = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , original_image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) A : Any = output.images[0] assert image.shape == (256, 256, 3) A : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 A : List[str] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" _start_torch_memory_measurement() A : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : List[Any] = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , mask_image=SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE , output_type='''np''' , ) A : Any = output.images[0] assert image.shape == (64, 64, 3) A : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 A : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() A : int = torch.Generator(device='''cpu''' ).manual_seed(0 ) A : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) A : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE ) A : Dict = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE , negative_prompt_embeds=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , mask_image=SCREAMING_SNAKE_CASE , original_image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) A : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) A : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 A : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
3
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) _a : Tuple = logging.getLogger(__name__) _a : Any = {'facebook/bart-base': BartForConditionalGeneration} _a : List[str] = {'facebook/bart-base': BartTokenizer} def SCREAMING_SNAKE_CASE ( ) -> int: _lowerCAmelCase : int = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" ,type=_lowerCamelCase ,default=5 ,help="""The maximum total input sequence length after tokenization.""" ,) parser.add_argument( """--num_beams""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) ,) parser.add_argument( """--model_name_or_path""" ,type=_lowerCamelCase ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=_lowerCamelCase ,) parser.add_argument( """--config_name""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Pretrained config name or path if not the same as model_name""" ,) parser.add_argument( """--device""" ,type=_lowerCamelCase ,default="""cpu""" ,help="""Device where the model will be run""" ,) parser.add_argument("""--output_file_path""" ,type=_lowerCamelCase ,default=_lowerCamelCase ,help="""Where to store the final ONNX file.""" ) _lowerCAmelCase : Optional[Any] = parser.parse_args() return args def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Union[str, Any]="cpu" ) -> str: _lowerCAmelCase : List[str] = model_dict[model_name].from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = tokenizer_dict[model_name].from_pretrained(_lowerCamelCase ) if model_name in ["facebook/bart-base"]: _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : str = None _lowerCAmelCase : List[str] = 0 return huggingface_model, tokenizer def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : List[str] ,_lowerCamelCase : int ,_lowerCamelCase : List[Any] ,_lowerCamelCase : List[str] ) -> Tuple: model.eval() _lowerCAmelCase : str = None _lowerCAmelCase : int = torch.jit.script(BARTBeamSearchGenerator(_lowerCamelCase ) ) with torch.no_grad(): _lowerCAmelCase : List[Any] = """My friends are cool but they eat too many carbs.""" _lowerCAmelCase : Union[str, Any] = tokenizer([ARTICLE_TO_SUMMARIZE] ,max_length=1024 ,return_tensors="""pt""" ).to(model.device ) _lowerCAmelCase : Any = model.generate( inputs["""input_ids"""] ,attention_mask=inputs["""attention_mask"""] ,num_beams=_lowerCamelCase ,max_length=_lowerCamelCase ,early_stopping=_lowerCamelCase ,decoder_start_token_id=model.config.decoder_start_token_id ,) torch.onnx.export( _lowerCamelCase ,( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) ,_lowerCamelCase ,opset_version=14 ,input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] ,output_names=["""output_ids"""] ,dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } ,example_outputs=_lowerCamelCase ,) logger.info("""Model exported to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : List[str] = remove_dup_initializers(os.path.abspath(_lowerCamelCase ) ) logger.info("""Deduplicated and optimized model written to {}""".format(_lowerCamelCase ) ) _lowerCAmelCase : str = onnxruntime.InferenceSession(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = ort_sess.run( _lowerCamelCase ,{ """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(_lowerCamelCase ), """max_length""": np.array(_lowerCamelCase ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } ,) np.testing.assert_allclose(summary_ids.cpu().numpy() ,ort_out[0] ,rtol=1e-3 ,atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def SCREAMING_SNAKE_CASE ( ) -> Any: _lowerCAmelCase : Any = parse_args() _lowerCAmelCase : List[Any] = 5 _lowerCAmelCase : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO ,) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _lowerCAmelCase : Optional[Any] = torch.device(args.device ) _lowerCAmelCase , _lowerCAmelCase : List[str] = load_model_tokenizer(args.model_name_or_path ,_lowerCamelCase ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(_lowerCamelCase ) if args.max_length: _lowerCAmelCase : Dict = args.max_length if args.num_beams: _lowerCAmelCase : Dict = args.num_beams if args.output_file_path: _lowerCAmelCase : Any = args.output_file_path else: _lowerCAmelCase : Union[str, Any] = """BART.onnx""" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if __name__ == "__main__": main()
44
0
'''simple docstring''' import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __snake_case =logging.get_logger(__name__) def a_ ( lowerCamelCase : bool , lowerCamelCase : bool ): def run_func(lowerCamelCase : List[str] ): @wraps(lowerCamelCase ) def run_in_eager_mode(*lowerCamelCase : List[str] , **lowerCamelCase : Tuple ): return func(*lowerCamelCase , **lowerCamelCase ) @wraps(lowerCamelCase ) @tf.function(experimental_compile=lowerCamelCase ) def run_in_graph_mode(*lowerCamelCase : List[Any] , **lowerCamelCase : Any ): return func(*lowerCamelCase , **lowerCamelCase ) if do_eager_mode is True: if use_xla is not False: raise ValueError( 'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def a_ ( lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ): lowerCAmelCase = random.Random() lowerCAmelCase = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowerCamelCase , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : TensorFlowBenchmarkArguments lowerCamelCase : PretrainedConfig lowerCamelCase : str = "TensorFlow" @property def __UpperCAmelCase ( self : int ) -> Optional[int]: return tf.__version__ def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float: # initialize GPU on separate process lowerCAmelCase = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) lowerCAmelCase = self._prepare_inference_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return self._measure_speed(_inference ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float: lowerCAmelCase = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) lowerCAmelCase = self._prepare_train_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return self._measure_speed(_train ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> [Memory, Optional[MemorySummary]]: # initialize GPU on separate process if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , UpperCAmelCase__ ) lowerCAmelCase = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) lowerCAmelCase = self._prepare_inference_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return self._measure_memory(_inference ) def __UpperCAmelCase ( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> [Memory, Optional[MemorySummary]]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , UpperCAmelCase__ ) lowerCAmelCase = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) lowerCAmelCase = self._prepare_train_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return self._measure_memory(_train ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Callable[[], None]: lowerCAmelCase = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) lowerCAmelCase = ( hasattr(UpperCAmelCase__ , 'architectures' ) and isinstance(config.architectures , UpperCAmelCase__ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: lowerCAmelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model lowerCAmelCase = __import__('transformers' , fromlist=[model_class] ) lowerCAmelCase = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model_cls(UpperCAmelCase__ ) except ImportError: raise ImportError( F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: lowerCAmelCase = TF_MODEL_MAPPING[config.__class__](UpperCAmelCase__ ) # encoder-decoder has vocab size saved differently lowerCAmelCase = config.vocab_size if hasattr(UpperCAmelCase__ , 'vocab_size' ) else config.encoder.vocab_size lowerCAmelCase = random_input_ids(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , training=UpperCAmelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(UpperCAmelCase__ , training=UpperCAmelCase__ ) lowerCAmelCase = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Callable[[], None]: lowerCAmelCase = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' ) if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) lowerCAmelCase = ( hasattr(UpperCAmelCase__ , 'architectures' ) and isinstance(config.architectures , UpperCAmelCase__ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: lowerCAmelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model lowerCAmelCase = __import__('transformers' , fromlist=[model_class] ) lowerCAmelCase = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model_cls(UpperCAmelCase__ ) except ImportError: raise ImportError( F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: lowerCAmelCase = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](UpperCAmelCase__ ) # encoder-decoder has vocab size saved differently lowerCAmelCase = config.vocab_size if hasattr(UpperCAmelCase__ , 'vocab_size' ) else config.encoder.vocab_size lowerCAmelCase = random_input_ids(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): lowerCAmelCase = model(UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ )[0] lowerCAmelCase = tf.gradients(UpperCAmelCase__ , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): lowerCAmelCase = model(UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ )[0] lowerCAmelCase = tf.gradients(UpperCAmelCase__ , model.trainable_variables ) return gradients lowerCAmelCase = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : Optional[Any] ) -> float: with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' ) timeit.repeat(UpperCAmelCase__ , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average lowerCAmelCase = timeit.repeat( UpperCAmelCase__ , repeat=self.args.repeat , number=1_0 , ) return min(UpperCAmelCase__ ) / 10.0 except ResourceExhaustedError as e: self.print_fn(F'''Doesn\'t fit on GPU. {e}''' ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : Callable[[], None] ) -> [Memory, MemorySummary]: logger.info( 'Note that TensorFlow allocates more memory than ' 'it might need to speed up computation. ' 'The memory reported here corresponds to the memory ' 'reported by `nvidia-smi`, which can vary depending ' 'on total available memory on the GPU that is used.' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory' ' consumption line by line.' ) lowerCAmelCase = start_memory_tracing('transformers' ) if self.args.is_tpu: # tpu raise NotImplementedError( 'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking' ' with `args.memory=False`' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( 'py3nvml not installed, we won\'t log GPU memory usage. ' 'Install py3nvml (pip install py3nvml) to log information about GPU.' ) lowerCAmelCase = 'N/A' else: logger.info( 'Measuring total GPU usage on GPU device. Make sure to not have additional processes' ' running on the same GPU.' ) # init nvml nvml.nvmlInit() func() lowerCAmelCase = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) lowerCAmelCase = nvml.nvmlDeviceGetMemoryInfo(UpperCAmelCase__ ) lowerCAmelCase = meminfo.used lowerCAmelCase = Memory(UpperCAmelCase__ ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( 'When enabling line by line tracing, the max peak memory for CPU is inaccurate in' ' TensorFlow.' ) lowerCAmelCase = None else: lowerCAmelCase = measure_peak_memory_cpu(UpperCAmelCase__ ) lowerCAmelCase = Memory(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else memory_bytes if self.args.trace_memory_line_by_line: lowerCAmelCase = stop_memory_tracing(UpperCAmelCase__ ) if memory is None: lowerCAmelCase = summary.total else: lowerCAmelCase = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F'''Doesn\'t fit on GPU. {e}''' ) return "N/A", None
4
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ) -> List[Any]: # noqa: E741 _lowerCAmelCase : Optional[int] = len(_lowerCamelCase ) _lowerCAmelCase : str = 0 _lowerCAmelCase : Any = [0] * n _lowerCAmelCase : str = [False] * n _lowerCAmelCase : str = [False] * n def dfs(_lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ): if parent == root: out_edge_count += 1 _lowerCAmelCase : Any = True _lowerCAmelCase : int = at for to in l[at]: if to == parent: pass elif not visited[to]: _lowerCAmelCase : Union[str, Any] = dfs(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : Optional[int] = min(low[at] ,low[to] ) # AP found via bridge if at < low[to]: _lowerCAmelCase : int = True # AP found via cycle if at == low[to]: _lowerCAmelCase : Tuple = True else: _lowerCAmelCase : Union[str, Any] = min(low[at] ,_lowerCamelCase ) return out_edge_count for i in range(_lowerCamelCase ): if not visited[i]: _lowerCAmelCase : int = 0 _lowerCAmelCase : Dict = dfs(_lowerCamelCase ,_lowerCamelCase ,-1 ,_lowerCamelCase ) _lowerCAmelCase : List[str] = out_edge_count > 1 for x in range(len(_lowerCamelCase ) ): if is_art[x] is True: print(_lowerCamelCase ) # Adjacency list of graph _a : Optional[Any] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
44
0
from __future__ import annotations def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case ) -> None: """simple docstring""" if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): _lowercase , _lowercase =array[indexa], array[indexa] def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case ) -> None: """simple docstring""" if length > 1: _lowercase =int(length / 2 ) for i in range(__snake_case , low + middle ): comp_and_swap(__snake_case , __snake_case , i + middle , __snake_case ) bitonic_merge(__snake_case , __snake_case , __snake_case , __snake_case ) bitonic_merge(__snake_case , low + middle , __snake_case , __snake_case ) def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case ) -> None: """simple docstring""" if length > 1: _lowercase =int(length / 2 ) bitonic_sort(__snake_case , __snake_case , __snake_case , 1 ) bitonic_sort(__snake_case , low + middle , __snake_case , 0 ) bitonic_merge(__snake_case , __snake_case , __snake_case , __snake_case ) if __name__ == "__main__": UpperCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase__ = [int(item.strip()) for item in user_input.split(''',''')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('''\nSorted array in ascending order is: ''', end='''''') print(*unsorted, sep=''', ''') bitonic_merge(unsorted, 0, len(unsorted), 0) print('''Sorted array in descending order is: ''', end='''''') print(*unsorted, sep=''', ''')
5
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = XGLMTokenizer _UpperCamelCase : List[Any] = XGLMTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : Tuple = True def __A ( self ): super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[str] = """<pad>""" _lowerCAmelCase : List[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 __A ( self ): _lowerCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(a__ ) , 1008 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __A ( self ): _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Any = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def __A ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) _lowerCAmelCase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=a__ ) _lowerCAmelCase : List[str] = pickle.dumps(a__ ) pickle.loads(a__ ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = self.get_rust_tokenizer() _lowerCAmelCase : Tuple = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : List[Any] = tokenizer.tokenize(a__ ) _lowerCAmelCase : Tuple = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : str = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = self.get_rust_tokenizer() _lowerCAmelCase : Dict = tokenizer.encode(a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __A ( self ): _lowerCAmelCase : int = """Hello World!""" _lowerCAmelCase : Optional[int] = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Any = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _lowerCAmelCase : List[str] = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : List[str] = { """input_ids""": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/xglm-564M""" , padding=a__ , )
44
0
import random class __A: @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case ) -> tuple[list[int], list[int]]: '''simple docstring''' __a = [ord(_snake_case ) for i in text] __a = [] __a = [] for i in plain: __a = random.randint(1 , 300 ) __a = (i + k) * k cipher.append(_snake_case ) key.append(_snake_case ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case , _snake_case ) -> str: '''simple docstring''' __a = [] for i in range(len(_snake_case ) ): __a = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(_snake_case ) ) return "".join(_snake_case ) if __name__ == "__main__": A , A : Any = Onepad().encrypt('Hello') print(c, k) print(Onepad().decrypt(c, k))
6
"""simple docstring""" from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : int ) -> List[str]: _lowerCAmelCase : Tuple = k_size // 2 _lowerCAmelCase , _lowerCAmelCase : List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] _lowerCAmelCase : Union[str, Any] = 1 / (2 * pi * sigma) * exp(-(square(_lowerCamelCase ) + square(_lowerCamelCase )) / (2 * square(_lowerCamelCase )) ) return g def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> Dict: _lowerCAmelCase , _lowerCAmelCase : str = image.shape[0], image.shape[1] # dst image height and width _lowerCAmelCase : Optional[int] = height - k_size + 1 _lowerCAmelCase : Dict = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows _lowerCAmelCase : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) _lowerCAmelCase : int = 0 for i, j in product(range(_lowerCamelCase ) ,range(_lowerCamelCase ) ): _lowerCAmelCase : Any = ravel(image[i : i + k_size, j : j + k_size] ) _lowerCAmelCase : Union[str, Any] = window row += 1 # turn the kernel into shape(k*k, 1) _lowerCAmelCase : List[Any] = gen_gaussian_kernel(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = ravel(_lowerCamelCase ) # reshape and get the dst image _lowerCAmelCase : int = dot(_lowerCamelCase ,_lowerCamelCase ).reshape(_lowerCamelCase ,_lowerCamelCase ).astype(_lowerCamelCase ) return dst if __name__ == "__main__": # read original image _a : Optional[Any] = imread(r'../image_data/lena.jpg') # turn image in gray scale value _a : Dict = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _a : Union[str, Any] = gaussian_filter(gray, 3, sigma=1) _a : List[Any] = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
44
0
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def _snake_case( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=1024 ) -> Union[str, Any]: '''simple docstring''' A__ , A__ = [], [] A__ = list(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) A__ , A__ = sorted_examples[0] def is_too_big(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return tok(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): A__ = new_src + ' ' + src A__ = new_tgt + ' ' + tgt if is_too_big(SCREAMING_SNAKE_CASE__ ) or is_too_big(SCREAMING_SNAKE_CASE__ ): # cant fit, finalize example finished_src.append(SCREAMING_SNAKE_CASE__ ) finished_tgt.append(SCREAMING_SNAKE_CASE__ ) A__ , A__ = src, tgt else: # can fit, keep adding A__ , A__ = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(SCREAMING_SNAKE_CASE__ ) finished_tgt.append(SCREAMING_SNAKE_CASE__ ) return finished_src, finished_tgt def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Path , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: '''simple docstring''' A__ = Path(SCREAMING_SNAKE_CASE__ ) save_path.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) for split in ["train"]: A__ , A__ = data_dir / f'{split}.source', data_dir / f'{split}.target' A__ = [x.rstrip() for x in Path(SCREAMING_SNAKE_CASE__ ).open().readlines()] A__ = [x.rstrip() for x in Path(SCREAMING_SNAKE_CASE__ ).open().readlines()] A__ , A__ = pack_examples(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'packed {split} split from {len(SCREAMING_SNAKE_CASE__ )} examples -> {len(SCREAMING_SNAKE_CASE__ )}.' ) Path(save_path / f'{split}.source' ).open('w' ).write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) Path(save_path / f'{split}.target' ).open('w' ).write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) for split in ["val", "test"]: A__ , A__ = data_dir / f'{split}.source', data_dir / f'{split}.target' shutil.copyfile(SCREAMING_SNAKE_CASE__ , save_path / f'{split}.source' ) shutil.copyfile(SCREAMING_SNAKE_CASE__ , save_path / f'{split}.target' ) def _snake_case( ) -> Optional[int]: '''simple docstring''' A__ = argparse.ArgumentParser() parser.add_argument('--tok_name' , type=SCREAMING_SNAKE_CASE__ , help='like facebook/bart-large-cnn,t5-base, etc.' ) parser.add_argument('--max_seq_len' , type=SCREAMING_SNAKE_CASE__ , default=128 ) parser.add_argument('--data_dir' , type=SCREAMING_SNAKE_CASE__ ) parser.add_argument('--save_path' , type=SCREAMING_SNAKE_CASE__ ) A__ = parser.parse_args() A__ = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(SCREAMING_SNAKE_CASE__ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
7
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
0
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=7 ): snake_case_ = None if token is not None: snake_case_ = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) snake_case_ = '''636036''' snake_case_ = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' snake_case_ = requests.get(SCREAMING_SNAKE_CASE__ , headers=SCREAMING_SNAKE_CASE__ ).json() return result["workflow_runs"] def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = get_daily_ci_runs(SCREAMING_SNAKE_CASE__ ) snake_case_ = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": snake_case_ = workflow_run['''id'''] break return workflow_run_id def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = get_last_daily_ci_runs(SCREAMING_SNAKE_CASE__ ) if workflow_run_id is not None: snake_case_ = get_artifacts_links(worflow_run_id=SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: snake_case_ = artifacts_links[artifact_name] download_artifact( artifact_name=SCREAMING_SNAKE_CASE__ , artifact_url=SCREAMING_SNAKE_CASE__ , output_dir=SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): get_last_daily_ci_artifacts(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case_ = {} for artifact_name in artifact_names: snake_case_ = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{artifact_name}.zip''' ) if os.path.isfile(SCREAMING_SNAKE_CASE__ ): snake_case_ = {} with zipfile.ZipFile(SCREAMING_SNAKE_CASE__ ) as z: for filename in z.namelist(): if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): # read the file with z.open(SCREAMING_SNAKE_CASE__ ) as f: snake_case_ = f.read().decode('''UTF-8''' ) return results
8
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __lowerCAmelCase : Optional[int] =logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} __lowerCAmelCase : List[str] ={ 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } __lowerCAmelCase : Optional[int] ={ 'gpt-neox-20b': 2_0_4_8, } class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Dict = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self :int , lowerCAmelCase__ :Any=None , lowerCAmelCase__ :Optional[Any]=None , lowerCAmelCase__ :List[Any]=None , lowerCAmelCase__ :str="<|endoftext|>" , lowerCAmelCase__ :str="<|endoftext|>" , lowerCAmelCase__ :Dict="<|endoftext|>" , lowerCAmelCase__ :Union[str, Any]=False , **lowerCAmelCase__ :List[str] , ) -> Any: super().__init__( lowerCAmelCase__ , lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , lowerCAmelCase__ ) != add_prefix_space: __SCREAMING_SNAKE_CASE : List[str] = getattr(lowerCAmelCase__ , pre_tok_state.pop('''type''' ) ) __SCREAMING_SNAKE_CASE : str = add_prefix_space __SCREAMING_SNAKE_CASE : Any = pre_tok_class(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = add_prefix_space def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :str , lowerCAmelCase__ :Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE : List[str] = self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ ) def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :"Conversation" ) -> List[int]: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) + [self.eos_token_id] ) if len(lowerCAmelCase__ ) > self.model_max_length: __SCREAMING_SNAKE_CASE : List[str] = input_ids[-self.model_max_length :] return input_ids
9
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 50 ) -> int: _lowerCAmelCase : int = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
44
0
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" lowerCamelCase__: Optional[int] =tmp_path / "file.csv" lowerCamelCase__: Optional[int] =textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20\n " ) with open(__a , "w" ) as f: f.write(__a ) return str(__a ) @pytest.fixture def lowerCAmelCase_ ( __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: str =tmp_path / "malformed_file.csv" lowerCamelCase__: List[Any] =textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20,\n " ) with open(__a , "w" ) as f: f.write(__a ) return str(__a ) @pytest.fixture def lowerCAmelCase_ ( __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "csv_with_image.csv" lowerCamelCase__: str =textwrap.dedent( F"""\ image {image_file} """ ) with open(__a , "w" ) as f: f.write(__a ) return str(__a ) @pytest.fixture def lowerCAmelCase_ ( __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "csv_with_label.csv" lowerCamelCase__: Optional[Any] =textwrap.dedent( "\\n label\n good\n bad\n good\n " ) with open(__a , "w" ) as f: f.write(__a ) return str(__a ) @pytest.fixture def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" lowerCamelCase__: Dict =tmp_path / "csv_with_int_list.csv" lowerCamelCase__: str =textwrap.dedent( "\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n " ) with open(__a , "w" ) as f: f.write(__a ) return str(__a ) def lowerCAmelCase_ ( __a , __a , __a ) -> str: """simple docstring""" lowerCamelCase__: List[Any] =Csv() lowerCamelCase__: Union[str, Any] =csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(__a , match="Error tokenizing data" ): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(__a ) in record.message for record in caplog.records ) @require_pil def lowerCAmelCase_ ( __a ) -> Dict: """simple docstring""" with open(__a , encoding="utf-8" ) as f: lowerCamelCase__: Optional[Any] =f.read().splitlines()[1] lowerCamelCase__: Any =Csv(encoding="utf-8" , features=Features({"image": Image()} ) ) lowerCamelCase__: int =csv._generate_tables([[csv_file_with_image]] ) lowerCamelCase__: Tuple =pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("image" ).type == Image()() lowerCamelCase__: List[str] =pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" with open(__a , encoding="utf-8" ) as f: lowerCamelCase__: str =f.read().splitlines()[1:] lowerCamelCase__: Any =Csv(encoding="utf-8" , features=Features({"label": ClassLabel(names=["good", "bad"] )} ) ) lowerCamelCase__: Optional[int] =csv._generate_tables([[csv_file_with_label]] ) lowerCamelCase__: Dict =pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("label" ).type == ClassLabel(names=["good", "bad"] )() lowerCamelCase__: Optional[int] =pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"] ).straint(__a ) for label in labels] def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[Any] =Csv(encoding="utf-8" , sep="," , converters={"int_list": lambda __a : [int(__a ) for i in x.split()]} ) lowerCamelCase__: Tuple =csv._generate_tables([[csv_file_with_int_list]] ) lowerCamelCase__: Dict =pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("int_list" ).type ) lowerCamelCase__: Any =pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
10
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
0
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCAmelCase__ = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class lowerCAmelCase__ : '''simple docstring''' __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = "gelu" def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=5 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=2_0 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=0 , ) -> Any: _A : Optional[int] = parent _A : str = batch_size _A : Dict = seq_length _A : Any = is_training _A : Any = use_labels _A : Tuple = vocab_size _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : Optional[Any] = num_attention_heads _A : str = intermediate_size _A : int = hidden_dropout_prob _A : List[str] = attention_probs_dropout_prob _A : Any = max_position_embeddings _A : Any = eos_token_id _A : int = pad_token_id _A : Optional[Any] = bos_token_id def _lowerCamelCase ( self) -> Any: _A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size).clip(3 , self.vocab_size) _A : int = np.expand_dims(np.array([self.eos_token_id] * self.batch_size) , 1) _A : List[str] = np.concatenate([input_ids, eos_tensor] , axis=1) _A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _A : List[str] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A : Dict = prepare_pegasus_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase) return config, inputs_dict def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> List[Any]: _A : List[str] = 2_0 _A : Optional[Any] = model_class_name(__lowerCamelCase) _A : str = model.encode(inputs_dict["input_ids"]) _A , _A : List[Any] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _A : Tuple = model.init_cache(decoder_input_ids.shape[0] , __lowerCamelCase , __lowerCamelCase) _A : List[Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4") _A : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _A : str = model.decode( decoder_input_ids[:, :-1] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) _A : List[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4") _A : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__lowerCamelCase , ) _A : List[str] = model.decode(__lowerCamelCase , __lowerCamelCase) _A : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}") def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Optional[Any]: _A : Union[str, Any] = 2_0 _A : Union[str, Any] = model_class_name(__lowerCamelCase) _A : str = model.encode(inputs_dict["input_ids"]) _A , _A : str = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _A : Optional[int] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])), ] , axis=-1 , ) _A : Tuple = model.init_cache(decoder_input_ids.shape[0] , __lowerCamelCase , __lowerCamelCase) _A : Optional[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _A : Optional[Any] = model.decode( decoder_input_ids[:, :-1] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) _A : Union[str, Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4") _A : List[str] = model.decode( decoder_input_ids[:, -1:] , __lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) _A : Optional[int] = model.decode(__lowerCamelCase , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase) _A : str = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}") def _UpperCAmelCase (UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[int]=None , ): if attention_mask is None: _A : Tuple = np.not_equal(UpperCamelCase__ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: _A : List[Any] = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class lowerCAmelCase__ ( a , unittest.TestCase): '''simple docstring''' __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def _lowerCamelCase ( self) -> Union[str, Any]: _A : List[str] = FlaxPegasusModelTester(self) _A : Optional[int] = ConfigTester(self , config_class=__lowerCamelCase) def _lowerCamelCase ( self) -> Union[str, Any]: self.config_tester.run_common_tests() def _lowerCamelCase ( self) -> str: _A , _A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self) -> Dict: _A , _A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self) -> Dict: _A , _A : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): _A : List[Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase) _A : Union[str, Any] = model_class(__lowerCamelCase) @jax.jit def encode_jitted(__lowerCamelCase , __lowerCamelCase=None , **__lowerCamelCase): return model.encode(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase) with self.subTest("JIT Enabled"): _A : Any = encode_jitted(**__lowerCamelCase).to_tuple() with self.subTest("JIT Disabled"): with jax.disable_jit(): _A : Union[str, Any] = encode_jitted(**__lowerCamelCase).to_tuple() self.assertEqual(len(__lowerCamelCase) , len(__lowerCamelCase)) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase): self.assertEqual(jitted_output.shape , output.shape) def _lowerCamelCase ( self) -> Dict: _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): _A : int = model_class(__lowerCamelCase) _A : Dict = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"]) _A : Union[str, Any] = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase): return model.decode( decoder_input_ids=__lowerCamelCase , decoder_attention_mask=__lowerCamelCase , encoder_outputs=__lowerCamelCase , ) with self.subTest("JIT Enabled"): _A : List[str] = decode_jitted(**__lowerCamelCase).to_tuple() with self.subTest("JIT Disabled"): with jax.disable_jit(): _A : Optional[int] = decode_jitted(**__lowerCamelCase).to_tuple() self.assertEqual(len(__lowerCamelCase) , len(__lowerCamelCase)) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase): self.assertEqual(jitted_output.shape , output.shape) @slow def _lowerCamelCase ( self) -> List[str]: for model_class_name in self.all_model_classes: _A : Tuple = model_class_name.from_pretrained("google/pegasus-large" , from_pt=__lowerCamelCase) _A : Union[str, Any] = np.ones((1, 1)) _A : Optional[int] = model(__lowerCamelCase) self.assertIsNotNone(__lowerCamelCase) @slow def _lowerCamelCase ( self) -> Tuple: _A : Optional[Any] = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum") _A : str = PegasusTokenizer.from_pretrained("google/pegasus-xsum") _A : Any = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] _A : List[Any] = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] _A : Any = tokenizer(__lowerCamelCase , return_tensors="np" , truncation=__lowerCamelCase , max_length=5_1_2 , padding=__lowerCamelCase) _A : List[Any] = model.generate(**__lowerCamelCase , num_beams=2).sequences _A : Optional[Any] = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase) assert tgt_text == decoded
11
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
0
from bisect import bisect from itertools import accumulate def lowerCamelCase__ ( A__ : List[Any] , A__ : Dict , A__ : str , A__ : Union[str, Any] ): '''simple docstring''' __lowerCamelCase = sorted(zip(A__ , A__ ) , key=lambda A__ : x[0] / x[1] , reverse=A__ ) __lowerCamelCase, __lowerCamelCase = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase = list(accumulate(A__ ) ) __lowerCamelCase = bisect(A__ , A__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
12
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
44
0
import os import pytest from transformers.dynamic_module_utils import get_imports lowerCAmelCase : str = """ import os """ lowerCAmelCase : Optional[Any] = """ def foo(): import os return False """ lowerCAmelCase : str = """ def foo(): def bar(): if True: import os return False return bar() """ lowerCAmelCase : Any = """ import os try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : int = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : Tuple = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar except ImportError as e: raise ValueError() """ lowerCAmelCase : List[str] = """ import os try: import bar except: raise ValueError() """ lowerCAmelCase : List[Any] = """ import os try: import bar import baz except ImportError: raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ lowerCAmelCase : Any = [ 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" , _UpperCAmelCase ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = os.path.join(_UpperCAmelCase , "test_file.py" ) with open(_UpperCAmelCase , "w" ) as _tmp_file: _tmp_file.write(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = get_imports(_UpperCAmelCase ) assert parsed_imports == ["os"]
13
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ): _lowerCAmelCase : Dict = parent _lowerCAmelCase : str = batch_size _lowerCAmelCase : List[Any] = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : Dict = use_input_mask _lowerCAmelCase : int = use_token_type_ids _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : Any = hidden_dropout_prob _lowerCAmelCase : List[str] = attention_probs_dropout_prob _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : List[str] = type_vocab_size _lowerCAmelCase : Tuple = type_sequence_label_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : Optional[Any] = num_choices _lowerCAmelCase : Tuple = relative_attention _lowerCAmelCase : Tuple = position_biased_input _lowerCAmelCase : Dict = pos_att_type _lowerCAmelCase : Any = scope def __A ( self ): _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : Optional[Any] = None if self.use_input_mask: _lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCAmelCase : str = None if self.use_token_type_ids: _lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return 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 , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self , a__ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] _lowerCAmelCase : List[Any] = model(a__ , token_type_ids=a__ )[0] _lowerCAmelCase : Any = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = DebertaVaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : int = self.num_labels _lowerCAmelCase : int = DebertaVaForSequenceClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = DebertaVaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[Any] = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Any = DebertaVaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = 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 __A ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ): _lowerCAmelCase : Union[str, Any] = DebertaVaForMultipleChoice(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCAmelCase : List[str] = model( a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ): _lowerCAmelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCAmelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _UpperCamelCase : str = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Optional[Any] = True _UpperCamelCase : List[Any] = False _UpperCamelCase : List[Any] = False _UpperCamelCase : Dict = False _UpperCamelCase : Tuple = False def __A ( self ): _lowerCAmelCase : Optional[Any] = DebertaVaModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def __A ( self ): _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def __A ( self ): _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*a__ ) @slow def __A ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Tuple = DebertaVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def __A ( self ): pass @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) _lowerCAmelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _lowerCAmelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCAmelCase : Optional[Any] = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. _lowerCAmelCase : str = torch.tensor( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F"{output[:, 1:4, 1:4]}" )
44
0
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase__ : str = "▁" , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[str, AddedToken] = "<unk>" , UpperCAmelCase__ : Union[str, AddedToken] = "</s>" , UpperCAmelCase__ : Union[str, AddedToken] = "<pad>" , ) ->Optional[Any]: '''simple docstring''' A__ = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } A__ = [None] * len(self.special_tokens) for token_dict in self.special_tokens.values(): A__ = token_dict['''token'''] A__ = Tokenizer(Unigram()) A__ = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''') , ''' '''), normalizers.Lowercase(), ]) A__ = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__), pre_tokenizers.Digits(individual_digits=UpperCAmelCase__), pre_tokenizers.Punctuation(), ]) A__ = decoders.Metaspace(replacement=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__) A__ = TemplateProcessing( single=f"""$A {self.special_tokens["eos"]["token"]}""" , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) A__ = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Union[str, List[str]] , UpperCAmelCase__ : int = 8_000 , UpperCAmelCase__ : bool = True , ) ->Tuple: '''simple docstring''' A__ = trainers.UnigramTrainer( vocab_size=UpperCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=UpperCAmelCase__ , ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = [files] self._tokenizer.train(UpperCAmelCase__ , trainer=UpperCAmelCase__) self.add_unk_id() def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Union[Iterator[str], Iterator[Iterator[str]]] , UpperCAmelCase__ : int = 8_000 , UpperCAmelCase__ : bool = True , ) ->List[Any]: '''simple docstring''' A__ = trainers.UnigramTrainer( vocab_size=UpperCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=UpperCAmelCase__ , ) self._tokenizer.train_from_iterator(UpperCAmelCase__ , trainer=UpperCAmelCase__) self.add_unk_id() def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = json.loads(self._tokenizer.to_str()) A__ = self.special_tokens['''unk''']['''id'''] A__ = Tokenizer.from_str(json.dumps(UpperCAmelCase__))
14
"""simple docstring""" import numpy as np import qiskit def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 8 ,_lowerCamelCase : int | None = None ) -> str: _lowerCAmelCase : int = np.random.default_rng(seed=_lowerCamelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. _lowerCAmelCase : Dict = rng.integers(2 ,size=_lowerCamelCase ) # The set of states Alice will prepare. _lowerCAmelCase : Tuple = rng.integers(2 ,size=_lowerCamelCase ) # Measurement basis for Bob's qubits. _lowerCAmelCase : Union[str, Any] = rng.integers(2 ,size=_lowerCamelCase ) # Quantum Circuit to simulate BB84 _lowerCAmelCase : Dict = qiskit.QuantumCircuit(_lowerCamelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if alice_state[index] == 1: bbaa_circ.x(_lowerCamelCase ) if alice_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_lowerCamelCase ): if bob_basis[index] == 1: bbaa_circ.h(_lowerCamelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCAmelCase : int = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCAmelCase : List[str] = qiskit.execute(_lowerCamelCase ,_lowerCamelCase ,shots=1 ,seed_simulator=_lowerCamelCase ) # Returns the result of measurement. _lowerCAmelCase : List[Any] = job.result().get_counts(_lowerCamelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCAmelCase : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCAmelCase : List[Any] = gen_key[:key_len] if len(_lowerCamelCase ) >= key_len else gen_key.ljust(_lowerCamelCase ,"""0""" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
44
0
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures SCREAMING_SNAKE_CASE :Optional[Any] = logging.get_logger(__name__) @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} ) snake_case_ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) snake_case_ = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.task_name.lower() class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "train" snake_case_ = "dev" snake_case_ = "test" class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = 42 def __init__( self : Union[str, Any] ,A : GlueDataTrainingArguments ,A : PreTrainedTokenizerBase ,A : Optional[int] = None ,A : Union[str, Split] = Split.train ,A : Optional[str] = None ,): warnings.warn( "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets " "library. You can have a look at this example script for pointers: " "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py" ,A ,) __A = args __A = glue_processors[args.task_name]() __A = glue_output_modes[args.task_name] if isinstance(A ,A ): try: __A = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) # Load data features from cache or dataset file __A = os.path.join( cache_dir if cache_dir is not None else args.data_dir ,f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' ,) __A = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) __A , __A = label_list[2], label_list[1] __A = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __A = cached_features_file + ".lock" with FileLock(A ): if os.path.exists(A ) and not args.overwrite_cache: __A = time.time() __A = torch.load(A ) logger.info( f'''Loading features from cached file {cached_features_file} [took %.3f s]''' ,time.time() - start ) else: logger.info(f'''Creating features from dataset file at {args.data_dir}''' ) if mode == Split.dev: __A = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: __A = self.processor.get_test_examples(args.data_dir ) else: __A = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: __A = examples[:limit_length] __A = glue_convert_examples_to_features( A ,A ,max_length=args.max_seq_length ,label_list=A ,output_mode=self.output_mode ,) __A = time.time() torch.save(self.features ,A ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self : int ): return len(self.features ) def __getitem__( self : Tuple ,A : List[Any] ): return self.features[i] def UpperCamelCase_ ( self : List[Any] ): return self.label_list
15
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _a : Union[str, Any] = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _a : List[str] = 10 _a : List[Any] = 256 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ) -> Optional[MinHash]: if len(_lowerCamelCase ) < MIN_NUM_TOKENS: return None _lowerCAmelCase : Optional[Any] = MinHash(num_perm=_lowerCamelCase ) for token in set(_lowerCamelCase ): min_hash.update(token.encode() ) return min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ) -> Set[str]: return {t for t in NON_ALPHA.split(_lowerCamelCase ) if len(t.strip() ) > 0} class __A : def __init__( self , *, a__ = 0.8_5 , ): _lowerCAmelCase : List[Any] = duplication_jaccard_threshold _lowerCAmelCase : Union[str, Any] = NUM_PERM _lowerCAmelCase : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase : Optional[int] = defaultdict(a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[Any] = self._index.query(a__ ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(a__ , a__ ) if len(a__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(a__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(a__ ) def __A ( self ): _lowerCAmelCase : int = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase : List[str] = [base] + list(a__ ) # reformat the cluster to be a list of dict _lowerCAmelCase : List[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(a__ ) return duplicate_clusters def __A ( self , a__ ): _lowerCAmelCase : Dict = self.get_duplicate_clusters() with open(a__ , """w""" ) as f: json.dump(a__ , a__ ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : Tuple = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ) -> Optional[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash ,ThreadedIterator(_lowerCamelCase ,max_queue_size=10000 ) ,chunksize=100 ,): if data is not None: yield data def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float ) -> List[str]: _lowerCAmelCase : Optional[Any] = DuplicationIndex(duplication_jaccard_threshold=_lowerCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_lowerCamelCase ) ) ,max_queue_size=100 ) ): di.add(_lowerCamelCase ,_lowerCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : str ,_lowerCamelCase : str ) -> float: _lowerCAmelCase : Any = get_tokens(_lowerCamelCase ) _lowerCAmelCase : Optional[int] = get_tokens(_lowerCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _a : str = None def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : List[Any] ) -> Dict: _lowerCAmelCase : int = [] for elementa in cluster: _lowerCAmelCase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: _lowerCAmelCase : Any = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(_lowerCamelCase ,_lowerCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase : Any = 1 extremes.append(_lowerCamelCase ) return extremes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Optional[Any] ,_lowerCamelCase : Any ) -> str: global _shared_dataset _lowerCAmelCase : Tuple = dataset _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Optional[Any] = partial(_find_cluster_extremes_shared ,jaccard_threshold=_lowerCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _lowerCamelCase ,_lowerCamelCase ,) ,total=len(_lowerCamelCase ) ,): extremes_list.append(_lowerCamelCase ) return extremes_list def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Type[Dataset] ,_lowerCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase : Tuple = make_duplicate_clusters(_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase : Optional[int] = {} _lowerCAmelCase : Tuple = find_extremes(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase : Union[str, Any] = element _lowerCAmelCase : List[Any] = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase : List[Any] = dataset.filter(lambda _lowerCamelCase ,_lowerCamelCase : idx not in remove_indices ,with_indices=_lowerCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase : Tuple = element["""base_index"""] in extreme_dict if element["is_extreme"]: _lowerCAmelCase : Dict = extreme_dict[element["""base_index"""]]["""copies"""] print(f"Original dataset size: {len(_lowerCamelCase )}" ) print(f"Number of duplicate clusters: {len(_lowerCamelCase )}" ) print(f"Files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_lowerCamelCase )}" ) print(f"Filtered dataset size: {len(_lowerCamelCase )}" ) return ds_filter, duplicate_clusters
44
0
"""simple docstring""" import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __A ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Tuple = inspect.getfile(accelerate.test_utils ) lowerCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_cli.py"] ) lowerCAmelCase : Tuple = ["accelerate", "launch"] lowerCAmelCase : Union[str, Any] = Path.home() / ".cache/huggingface/accelerate" lowerCAmelCase : Optional[int] = "default_config.yaml" lowerCAmelCase : Union[str, Any] = config_folder / config_file lowerCAmelCase : Union[str, Any] = config_folder / "_default_config.yaml" lowerCAmelCase : Optional[Any] = Path("tests/test_configs" ) @classmethod def UpperCAmelCase ( cls : Optional[Any] ) -> Optional[int]: """simple docstring""" if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def UpperCAmelCase ( cls : str ) -> Dict: """simple docstring""" if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def UpperCAmelCase ( self : Dict ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[int] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def UpperCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=_snake_case ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(_snake_case ), self.test_file_path] ,env=os.environ.copy() ) def UpperCAmelCase ( self : Tuple ) -> str: """simple docstring""" execute_subprocess_async(['''accelerate''', '''test'''] ,env=os.environ.copy() ) class __A ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase : str = "test-tpu" lowerCAmelCase : Dict = "us-central1-a" lowerCAmelCase : List[str] = "ls" lowerCAmelCase : Any = ["accelerate", "tpu-config"] lowerCAmelCase : Any = "cd /usr/share" lowerCAmelCase : Union[str, Any] = "tests/test_samples/test_command_file.sh" lowerCAmelCase : List[str] = "Running gcloud compute tpus tpu-vm ssh" def UpperCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" lowercase__ : Dict = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Any ) -> List[str]: """simple docstring""" lowercase__ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" lowercase__ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] ,return_stdout=_snake_case ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" lowercase__ : Optional[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Any ) -> int: """simple docstring""" lowercase__ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ : Optional[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Any ) -> List[str]: """simple docstring""" lowercase__ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" lowercase__ : int = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_snake_case ,) def UpperCAmelCase ( self : int ) -> List[str]: """simple docstring""" lowercase__ : Dict = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] ,return_stdout=_snake_case ,) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_snake_case ,)
16
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Any = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : int = "swinv2" _UpperCamelCase : List[str] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : int = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : List[Any] = embed_dim _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : List[Any] = len(a__ ) _lowerCAmelCase : Any = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : Tuple = mlp_ratio _lowerCAmelCase : Any = qkv_bias _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : str = drop_path_rate _lowerCAmelCase : List[str] = hidden_act _lowerCAmelCase : List[str] = use_absolute_embeddings _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Tuple = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : Tuple = (0, 0, 0, 0)
44
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _a = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
17
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A ( unittest.TestCase ): def __A ( self ): _lowerCAmelCase : Optional[int] = """ylacombe/bark-small""" _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : int = """en_speaker_1""" _lowerCAmelCase : List[Any] = """This is a test string""" _lowerCAmelCase : Any = """speaker_embeddings_path.json""" _lowerCAmelCase : List[Any] = """speaker_embeddings""" def __A ( self , **a__ ): return AutoTokenizer.from_pretrained(self.checkpoint , **a__ ) def __A ( self ): shutil.rmtree(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : int = BarkProcessor(tokenizer=a__ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self ): _lowerCAmelCase : Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _lowerCAmelCase : Tuple = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : List[Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self ): _lowerCAmelCase : List[str] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _lowerCAmelCase : Union[str, Any] = 35 _lowerCAmelCase : Union[str, Any] = 2 _lowerCAmelCase : Optional[int] = 8 _lowerCAmelCase : Dict = { """semantic_prompt""": np.ones(a__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _lowerCAmelCase : Dict = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Tuple = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _lowerCAmelCase : List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(a__ , **a__ ) _lowerCAmelCase : List[Any] = processor(text=self.input_string , voice_preset=a__ ) _lowerCAmelCase : Optional[int] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _lowerCAmelCase : str = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self ): _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : List[Any] = BarkProcessor(tokenizer=a__ ) _lowerCAmelCase : Dict = processor(text=self.input_string ) _lowerCAmelCase : Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
44
0
__lowerCamelCase : Union[str, Any] = { 0: '''0''', 1: '''1''', 2: '''2''', 3: '''3''', 4: '''4''', 5: '''5''', 6: '''6''', 7: '''7''', 8: '''8''', 9: '''9''', 10: '''a''', 11: '''b''', 12: '''c''', 13: '''d''', 14: '''e''', 15: '''f''', } def _snake_case ( lowerCAmelCase : float ): """simple docstring""" assert type(lowerCAmelCase ) in (int, float) and decimal == int(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : List[Any] = int(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Dict = "" SCREAMING_SNAKE_CASE_ : Any = False if decimal < 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = True decimal *= -1 while decimal > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = divmod(lowerCAmelCase , 1_6 ) SCREAMING_SNAKE_CASE_ : List[Any] = values[remainder] + hexadecimal SCREAMING_SNAKE_CASE_ : Optional[int] = "0x" + hexadecimal if negative: SCREAMING_SNAKE_CASE_ : Optional[int] = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
18
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Dict: _lowerCAmelCase : List[Any] = torch.exp(_lowerCamelCase ) _lowerCAmelCase : List[Any] = torch.sum(_lowerCamelCase ,dim=1 ) # sum of exp(x_i) _lowerCAmelCase : Dict = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : int = config.output_attentions _lowerCAmelCase : Any = config.output_hidden_states _lowerCAmelCase : List[Any] = nn.ModuleList([BertLayer(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : Any = nn.ModuleList([BertHighway(a__ ) for _ in range(config.num_hidden_layers )] ) _lowerCAmelCase : str = [-1 for _ in range(config.num_hidden_layers )] def __A ( self , a__ ): if (type(a__ ) is float) or (type(a__ ) is int): for i in range(len(self.early_exit_entropy ) ): _lowerCAmelCase : Tuple = x else: _lowerCAmelCase : Optional[int] = x def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __A ( self , a__ , a__=None , a__=None , a__=None , a__=None , ): _lowerCAmelCase : Any = () _lowerCAmelCase : Optional[int] = () _lowerCAmelCase : List[Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _lowerCAmelCase : str = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[str] = layer_module( a__ , a__ , head_mask[i] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = layer_outputs[0] if self.output_attentions: _lowerCAmelCase : Dict = all_attentions + (layer_outputs[1],) _lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Optional[int] = current_outputs + (all_attentions,) _lowerCAmelCase : Optional[Any] = self.highway[i](a__ ) # logits, pooled_output if not self.training: _lowerCAmelCase : Tuple = highway_exit[0] _lowerCAmelCase : Any = entropy(a__ ) _lowerCAmelCase : Optional[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _lowerCAmelCase : Union[str, Any] = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _lowerCAmelCase : List[str] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a__ , i + 1 ) else: _lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _lowerCAmelCase : List[Any] = all_hidden_states + (hidden_states,) _lowerCAmelCase : List[Any] = (hidden_states,) if self.output_hidden_states: _lowerCAmelCase : List[str] = outputs + (all_hidden_states,) if self.output_attentions: _lowerCAmelCase : Any = outputs + (all_attentions,) _lowerCAmelCase : Optional[int] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config _lowerCAmelCase : Tuple = BertEmbeddings(a__ ) _lowerCAmelCase : Tuple = DeeBertEncoder(a__ ) _lowerCAmelCase : List[str] = BertPooler(a__ ) self.init_weights() def __A ( self ): self.encoder.init_highway_pooler(self.pooler ) def __A ( self ): return self.embeddings.word_embeddings def __A ( self , a__ ): _lowerCAmelCase : Dict = value def __A ( self , a__ ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a__ ) @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _lowerCAmelCase : Any = input_ids.size() elif inputs_embeds is not None: _lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _lowerCAmelCase : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _lowerCAmelCase : List[Any] = torch.ones(a__ , device=a__ ) if encoder_attention_mask is None: _lowerCAmelCase : Optional[Any] = torch.ones(a__ , device=a__ ) if token_type_ids is None: _lowerCAmelCase : Dict = torch.zeros(a__ , dtype=torch.long , device=a__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(a__ , a__ , a__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _lowerCAmelCase : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _lowerCAmelCase : Tuple = encoder_attention_mask[:, None, None, :] _lowerCAmelCase : Union[str, Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _lowerCAmelCase : Optional[Any] = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _lowerCAmelCase : Optional[int] = self.get_head_mask(a__ , self.config.num_hidden_layers ) _lowerCAmelCase : Dict = self.embeddings( input_ids=a__ , position_ids=a__ , token_type_ids=a__ , inputs_embeds=a__ ) _lowerCAmelCase : Union[str, Any] = self.encoder( a__ , attention_mask=a__ , head_mask=a__ , encoder_hidden_states=a__ , encoder_attention_mask=a__ , ) _lowerCAmelCase : Dict = encoder_outputs[0] _lowerCAmelCase : Union[str, Any] = self.pooler(a__ ) _lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ , a__ ): _lowerCAmelCase : str = message _lowerCAmelCase : str = exit_layer # start from 1! class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Any = BertPooler(a__ ) _lowerCAmelCase : str = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def __A ( self , a__ ): # Pooler _lowerCAmelCase : Tuple = encoder_outputs[0] _lowerCAmelCase : int = self.pooler(a__ ) # "return" pooler_output # BertModel _lowerCAmelCase : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _lowerCAmelCase : Optional[int] = bmodel_output[1] _lowerCAmelCase : Tuple = self.dropout(a__ ) _lowerCAmelCase : Dict = self.classifier(a__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , SCREAMING_SNAKE_CASE_ , ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[str] = config.num_labels _lowerCAmelCase : Optional[Any] = config.num_hidden_layers _lowerCAmelCase : str = DeeBertModel(a__ ) _lowerCAmelCase : Tuple = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase : List[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a__ ) def __A ( self , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=None , a__=-1 , a__=False , ): _lowerCAmelCase : Dict = self.num_layers try: _lowerCAmelCase : str = self.bert( a__ , attention_mask=a__ , token_type_ids=a__ , position_ids=a__ , head_mask=a__ , inputs_embeds=a__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _lowerCAmelCase : Any = outputs[1] _lowerCAmelCase : Optional[int] = self.dropout(a__ ) _lowerCAmelCase : List[str] = self.classifier(a__ ) _lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : int = e.exit_layer _lowerCAmelCase : Union[str, Any] = outputs[0] if not self.training: _lowerCAmelCase : Tuple = entropy(a__ ) _lowerCAmelCase : Optional[int] = [] _lowerCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Tuple = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase : Optional[Any] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Dict = highway_exit[0] if not self.training: highway_logits_all.append(a__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase : Optional[int] = CrossEntropyLoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(a__ ) if train_highway: _lowerCAmelCase : List[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Dict = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Dict = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
0
from functools import reduce __A =( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def lowerCamelCase_ ( lowerCamelCase__ = N ): return max( # mypy cannot properly interpret reduce int(reduce(lambda lowerCamelCase__ , lowerCamelCase__ : str(int(lowerCamelCase__ ) * int(lowerCamelCase__ ) ) , n[i : i + 1_3] ) ) for i in range(len(lowerCamelCase__ ) - 1_2 ) ) if __name__ == "__main__": print(F"""{solution() = }""")
19
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : str = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , a__ = None , a__ = None , **a__ , ): super().__init__(self , **a__ ) _lowerCAmelCase : Any = repo_info _lowerCAmelCase : Optional[Any] = token _lowerCAmelCase : Optional[int] = None def __A ( self ): if self.dir_cache is None: _lowerCAmelCase : Optional[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowerCAmelCase : 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 __A ( self , a__ , a__ = "rb" , **a__ , ): if not isinstance(self.repo_info , a__ ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) _lowerCAmelCase : Tuple = 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 __A ( self , a__ , **a__ ): self._get_dirs() _lowerCAmelCase : Union[str, Any] = self._strip_protocol(a__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a__ ) def __A ( self , a__ , a__=False , **a__ ): self._get_dirs() _lowerCAmelCase : Any = PurePosixPath(path.strip("""/""" ) ) _lowerCAmelCase : List[str] = {} for p, f in self.dir_cache.items(): _lowerCAmelCase : Any = PurePosixPath(p.strip("""/""" ) ) _lowerCAmelCase : Optional[int] = p.parent if root == path: _lowerCAmelCase : Dict = f _lowerCAmelCase : Union[str, Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
44
0