code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase = {'configuration_glpn': ['GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GLPNConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['GLPNFeatureExtractor'] UpperCamelCase = ['GLPNImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'GLPN_PRETRAINED_MODEL_ARCHIVE_LIST', 'GLPNForDepthEstimation', 'GLPNLayer', 'GLPNModel', 'GLPNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase = {'configuration_van': ['VAN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VanConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'VAN_PRETRAINED_MODEL_ARCHIVE_LIST', 'VanForImageClassification', 'VanModel', 'VanPreTrainedModel', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure)
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
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 DetaImageProcessor class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict=7 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : Any=30 , SCREAMING_SNAKE_CASE__ : int=400 , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[int]=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=1 / 255 , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> List[str]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCAmelCase__ = size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean lowerCAmelCase__ = image_std lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_pad def a ( self : Dict ) -> Optional[Any]: 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 : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int=False ) -> Dict: if not batched: lowerCAmelCase__ = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): lowerCAmelCase__ , lowerCAmelCase__ = image.size else: lowerCAmelCase__ , lowerCAmelCase__ = image.shape[1], image.shape[2] if w < h: lowerCAmelCase__ = int(self.size["shortest_edge"] * h / w ) lowerCAmelCase__ = self.size["shortest_edge"] elif w > h: lowerCAmelCase__ = self.size["shortest_edge"] lowerCAmelCase__ = int(self.size["shortest_edge"] * w / h ) else: lowerCAmelCase__ = self.size["shortest_edge"] lowerCAmelCase__ = self.size["shortest_edge"] else: lowerCAmelCase__ = [] for image in image_inputs: lowerCAmelCase__ , lowerCAmelCase__ = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = DetaImageProcessor if is_vision_available() else None def a ( self : str ) -> Tuple: lowerCAmelCase__ = DetaImageProcessingTester(self ) @property def a ( self : List[Any] ) -> List[str]: return self.image_processor_tester.prepare_image_processor_dict() def a ( self : int ) -> List[str]: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_mean" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_std" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_normalize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_rescale" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_pad" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) def a ( self : int ) -> List[Any]: lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> int: pass def a ( self : Union[str, Any] ) -> str: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 : Dict ) -> Optional[int]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a ( self : Dict ) -> Optional[Any]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) 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 : Tuple ) -> List[Any]: # prepare image and target lowerCAmelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: lowerCAmelCase__ = json.loads(f.read() ) lowerCAmelCase__ = {"image_id": 39_769, "annotations": target} # encode them lowerCAmelCase__ = DetaImageProcessor() lowerCAmelCase__ = image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) # verify pixel values lowerCAmelCase__ = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area lowerCAmelCase__ = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes lowerCAmelCase__ = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id lowerCAmelCase__ = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd lowerCAmelCase__ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels lowerCAmelCase__ = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size lowerCAmelCase__ = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , SCREAMING_SNAKE_CASE__ ) ) # verify size lowerCAmelCase__ = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , SCREAMING_SNAKE_CASE__ ) ) @slow def a ( self : Optional[int] ) -> Optional[Any]: # prepare image, target and masks_path lowerCAmelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: lowerCAmelCase__ = json.loads(f.read() ) lowerCAmelCase__ = {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target} lowerCAmelCase__ = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them lowerCAmelCase__ = DetaImageProcessor(format="coco_panoptic" ) lowerCAmelCase__ = image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) # verify pixel values lowerCAmelCase__ = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area lowerCAmelCase__ = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes lowerCAmelCase__ = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id lowerCAmelCase__ = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd lowerCAmelCase__ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels lowerCAmelCase__ = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , SCREAMING_SNAKE_CASE__ ) ) # verify masks lowerCAmelCase__ = 822_873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size lowerCAmelCase__ = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , SCREAMING_SNAKE_CASE__ ) ) # verify size lowerCAmelCase__ = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , SCREAMING_SNAKE_CASE__ ) )
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
import math class __lowerCamelCase : """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 ) -> Optional[Any]: # a graph with Node 0,1,...,N-1 lowerCAmelCase__ = n lowerCAmelCase__ = [ [math.inf for j in range(0 , SCREAMING_SNAKE_CASE__ )] for i in range(0 , SCREAMING_SNAKE_CASE__ ) ] # adjacency matrix for weight lowerCAmelCase__ = [ [math.inf for j in range(0 , SCREAMING_SNAKE_CASE__ )] for i in range(0 , SCREAMING_SNAKE_CASE__ ) ] # dp[i][j] stores minimum distance from i to j def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: lowerCAmelCase__ = w def a ( self : Any ) -> Optional[int]: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): lowerCAmelCase__ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: return self.dp[u][v] if __name__ == "__main__": UpperCamelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) def _A ( lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : Union[int, Iterable[int]] , lowerCAmelCase_ : bool , lowerCAmelCase_ : int ): """simple docstring""" def constraint_to_multiple_of(lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any]=0 , lowerCAmelCase_ : List[Any]=None ): lowerCAmelCase__ = round(val / multiple ) * multiple if max_val is not None and x > max_val: lowerCAmelCase__ = math.floor(val / multiple ) * multiple if x < min_val: lowerCAmelCase__ = math.ceil(val / multiple ) * multiple return x lowerCAmelCase__ = (output_size, output_size) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else output_size lowerCAmelCase__ , lowerCAmelCase__ = get_image_size(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = output_size # determine new height and width lowerCAmelCase__ = output_height / input_height lowerCAmelCase__ = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width lowerCAmelCase__ = scale_width else: # fit height lowerCAmelCase__ = scale_height lowerCAmelCase__ = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCAmelCase_ ) lowerCAmelCase__ = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCAmelCase_ ) return (new_height, new_width) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"height": 384, "width": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = keep_aspect_ratio lowerCAmelCase__ = ensure_multiple_of lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) lowerCAmelCase__ = get_resize_output_image_size( SCREAMING_SNAKE_CASE__ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE__ , multiple=SCREAMING_SNAKE_CASE__ , ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> Dict: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : str , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : int = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : int = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : int , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio lowerCAmelCase__ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Tuple] = None ) -> Dict: lowerCAmelCase__ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = target_sizes.numpy() lowerCAmelCase__ = [] for idx in range(len(SCREAMING_SNAKE_CASE__ ) ): lowerCAmelCase__ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = logits.argmax(dim=1 ) lowerCAmelCase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
61
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
1
import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available 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 torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : List[str]=32 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Dict=10 , SCREAMING_SNAKE_CASE__ : str=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE__ : Any=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Dict=None , ) -> Dict: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = embeddings_size lowerCAmelCase__ = hidden_sizes lowerCAmelCase__ = depths lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_act lowerCAmelCase__ = num_labels lowerCAmelCase__ = scope lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> List[str]: lowerCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : Tuple ) -> str: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: lowerCAmelCase__ = RegNetModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = RegNetForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a ( self : List[Any] ) -> int: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[Any] ) -> List[Any]: lowerCAmelCase__ = RegNetModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> Dict: 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 : Any ) -> Dict: return @unittest.skip(reason="RegNet does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Dict: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def a ( self : List[Any] ) -> Dict: pass def a ( self : Tuple ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> Dict: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Any ) -> List[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(config=SCREAMING_SNAKE_CASE__ ) for name, module in model.named_modules(): if isinstance(SCREAMING_SNAKE_CASE__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) def a ( self : int ) -> Optional[Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCAmelCase__ = layer_type lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> List[str]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : Dict ) -> List[str]: for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = RegNetModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Dict ) -> List[Any]: return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def a ( self : Tuple ) -> Any: lowerCAmelCase__ = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.4_180, -1.5_051, -3.4_836] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'facebook/data2vec-vision-base-ft': ( 'https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json' ), } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "data2vec-vision" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict=768 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Any=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-1_2 , SCREAMING_SNAKE_CASE__ : Tuple=224 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any=3 , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=[3, 5, 7, 11] , SCREAMING_SNAKE_CASE__ : Optional[int]=[1, 2, 3, 6] , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[int]=0.4 , SCREAMING_SNAKE_CASE__ : Dict=256 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=255 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = use_mask_token lowerCAmelCase__ = use_absolute_position_embeddings lowerCAmelCase__ = use_relative_position_bias lowerCAmelCase__ = use_shared_relative_position_bias lowerCAmelCase__ = layer_scale_init_value lowerCAmelCase__ = drop_path_rate lowerCAmelCase__ = use_mean_pooling # decode head attributes (semantic segmentation) lowerCAmelCase__ = out_indices lowerCAmelCase__ = pool_scales # auxiliary head attributes (semantic segmentation) lowerCAmelCase__ = use_auxiliary_head lowerCAmelCase__ = auxiliary_loss_weight lowerCAmelCase__ = auxiliary_channels lowerCAmelCase__ = auxiliary_num_convs lowerCAmelCase__ = auxiliary_concat_input lowerCAmelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = version.parse("1.11" ) @property def a ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def a ( self : Optional[Any] ) -> float: return 1e-4
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
import random from .binary_exp_mod import bin_exp_mod def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[int]=1000 ): """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd lowerCAmelCase__ = n - 1 lowerCAmelCase__ = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) lowerCAmelCase__ = 0 while count < prec: lowerCAmelCase__ = random.randint(2 , n - 1 ) lowerCAmelCase__ = bin_exp_mod(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if b != 1: lowerCAmelCase__ = True for _ in range(lowerCAmelCase_ ): if b == n - 1: lowerCAmelCase__ = False break lowerCAmelCase__ = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": UpperCamelCase = abs(int(input('Enter bound : ').strip())) print('Here\'s the list of primes:') print(', '.join(str(i) for i in range(n + 1) if is_prime_big(i)))
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = [ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def _A ( lowerCAmelCase_ : Any ): """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: lowerCAmelCase__ = k.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if k.startswith("encoder" ): lowerCAmelCase__ = k.replace(".attn" , ".self_attn" ) lowerCAmelCase__ = k.replace("norm1" , "self_attn_layer_norm" ) lowerCAmelCase__ = k.replace("norm2" , "final_layer_norm" ) elif k.startswith("decoder" ): lowerCAmelCase__ = k.replace("norm1" , "self_attn_layer_norm" ) lowerCAmelCase__ = k.replace("norm2" , "encoder_attn_layer_norm" ) lowerCAmelCase__ = k.replace("norm3" , "final_layer_norm" ) return k def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = [ "model.encoder.layernorm_embedding.weight", "model.encoder.layernorm_embedding.bias", "model.decoder.layernorm_embedding.weight", "model.decoder.layernorm_embedding.bias", ] for k in keys: lowerCAmelCase__ = sd.pop(lowerCAmelCase_ ) lowerCAmelCase__ = k.replace("layernorm_embedding" , "layer_norm" ) assert new_k not in sd lowerCAmelCase__ = v UpperCamelCase = ['START'] @torch.no_grad() def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = torch.load(lowerCAmelCase_ , map_location="cpu" ) lowerCAmelCase__ = model["model"] lowerCAmelCase__ = BlenderbotConfig.from_json_file(lowerCAmelCase_ ) lowerCAmelCase__ = BlenderbotForConditionalGeneration(lowerCAmelCase_ ) lowerCAmelCase__ = m.model.state_dict().keys() lowerCAmelCase__ = [] lowerCAmelCase__ = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue lowerCAmelCase__ = rename_state_dict_key(lowerCAmelCase_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: lowerCAmelCase__ = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(lowerCAmelCase_ ) m.model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) m.half() m.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) UpperCamelCase = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
from __future__ import annotations from collections import deque class __lowerCamelCase : """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : list[str] ) -> Optional[int]: lowerCAmelCase__ = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(SCREAMING_SNAKE_CASE__ ) self.set_fail_transitions() def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str ) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = 0 for character in keyword: lowerCAmelCase__ = self.find_next_state(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) lowerCAmelCase__ = len(self.adlist ) - 1 else: lowerCAmelCase__ = next_state self.adlist[current_state]["output"].append(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> None: lowerCAmelCase__ = deque() for node in self.adlist[0]["next_states"]: q.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 0 while q: lowerCAmelCase__ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.adlist[r]["fail_state"] while ( self.find_next_state(SCREAMING_SNAKE_CASE__ , self.adlist[child]["value"] ) is None and state != 0 ): lowerCAmelCase__ = self.adlist[state]["fail_state"] lowerCAmelCase__ = self.find_next_state( SCREAMING_SNAKE_CASE__ , self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: lowerCAmelCase__ = 0 lowerCAmelCase__ = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def a ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> dict[str, list[int]]: lowerCAmelCase__ = {} # returns a dict with keywords and list of its occurrences lowerCAmelCase__ = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): while ( self.find_next_state(SCREAMING_SNAKE_CASE__ , string[i] ) is None and current_state != 0 ): lowerCAmelCase__ = self.adlist[current_state]["fail_state"] lowerCAmelCase__ = self.find_next_state(SCREAMING_SNAKE_CASE__ , string[i] ) if next_state is None: lowerCAmelCase__ = 0 else: lowerCAmelCase__ = next_state for key in self.adlist[current_state]["output"]: if key not in result: lowerCAmelCase__ = [] result[key].append(i - len(SCREAMING_SNAKE_CASE__ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
1
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : LevitConfig , lowerCAmelCase_ : Path , lowerCAmelCase_ : bool = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": lowerCAmelCase__ = timm.create_model("levit_128s" , pretrained=lowerCAmelCase_ ) else: lowerCAmelCase__ = timm.create_model("levit_128" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 192: lowerCAmelCase__ = timm.create_model("levit_192" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 256: lowerCAmelCase__ = timm.create_model("levit_256" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 384: lowerCAmelCase__ = timm.create_model("levit_384" , pretrained=lowerCAmelCase_ ) from_model.eval() lowerCAmelCase__ = LevitForImageClassificationWithTeacher(lowerCAmelCase_ ).eval() lowerCAmelCase__ = OrderedDict() lowerCAmelCase__ = from_model.state_dict() lowerCAmelCase__ = list(from_model.state_dict().keys() ) lowerCAmelCase__ = list(our_model.state_dict().keys() ) print(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for i in range(len(lowerCAmelCase_ ) ): lowerCAmelCase__ = weights[og_keys[i]] our_model.load_state_dict(lowerCAmelCase_ ) lowerCAmelCase__ = torch.randn((2, 3, 224, 224) ) lowerCAmelCase__ = from_model(lowerCAmelCase_ ) lowerCAmelCase__ = our_model(lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ ), "The model logits don't match the original one." lowerCAmelCase__ = name print(lowerCAmelCase_ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) lowerCAmelCase__ = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'Pushed {checkpoint_name}' ) def _A ( lowerCAmelCase_ : Path , lowerCAmelCase_ : str = None , lowerCAmelCase_ : bool = True ): """simple docstring""" lowerCAmelCase__ = "imagenet-1k-id2label.json" lowerCAmelCase__ = 1000 lowerCAmelCase__ = (1, num_labels) lowerCAmelCase__ = "huggingface/label-files" lowerCAmelCase__ = num_labels lowerCAmelCase__ = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} lowerCAmelCase__ = idalabel lowerCAmelCase__ = {v: k for k, v in idalabel.items()} lowerCAmelCase__ = partial(lowerCAmelCase_ , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid=lowerCAmelCase_ ) lowerCAmelCase__ = { "levit-128S": 128, "levit-128": 128, "levit-192": 192, "levit-256": 256, "levit-384": 384, } lowerCAmelCase__ = { "levit-128S": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), "levit-128": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), "levit-192": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), "levit-256": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), "levit-384": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , lowerCAmelCase_ , names_to_config[model_name] , lowerCAmelCase_ , lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help='The name of the model you wish to convert, it must be one of the supported Levit* architecture,', ) parser.add_argument( '--pytorch_dump_folder_path', default='levit-dump-folder/', type=Path, required=False, help='Path to the output PyTorch model directory.', ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = (KDPMaDiscreteScheduler,) snake_case__ = 1_0 def a ( self : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Tuple: lowerCAmelCase__ = { "num_train_timesteps": 1_100, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**SCREAMING_SNAKE_CASE__ ) return config def a ( self : Optional[Any] ) -> Union[str, Any]: for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> Optional[int]: for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> List[Any]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Optional[Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(prediction_type="v_prediction" ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_9_3_4e-0_7 ) < 1e-2 assert abs(result_mean.item() - 6.1_1_1_2e-1_0 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2e-0_7 ) < 1e-2 assert abs(result_mean.item() - 0.0_002 ) < 1e-3 def a ( self : Dict ) -> Tuple: if torch_device == "mps": return lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 def a ( self : Optional[int] ) -> Dict: if torch_device == "mps": return lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if str(SCREAMING_SNAKE_CASE__ ).startswith("cpu" ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = RemBertConfig.from_json_file(lowerCAmelCase_ ) print("Building PyTorch model from configuration: {}".format(str(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = RemBertModel(lowerCAmelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_rembert(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Save pytorch-model print("Save PyTorch model to {}".format(lowerCAmelCase_ ) ) torch.save(model.state_dict() , lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--rembert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained RemBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) UpperCamelCase = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
from itertools import permutations def _A ( lowerCAmelCase_ : tuple ): """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False lowerCAmelCase__ = [7, 11, 13, 17] for i, test in enumerate(lowerCAmelCase_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A ( lowerCAmelCase_ : int = 10 ): """simple docstring""" return sum( int("".join(map(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) for num in permutations(range(lowerCAmelCase_ ) ) if is_substring_divisible(lowerCAmelCase_ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
UpperCamelCase = '0.18.2' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
class __lowerCamelCase : """simple docstring""" def __init__( self : int , SCREAMING_SNAKE_CASE__ : list ) -> None: lowerCAmelCase__ = set_counts lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = [1] * num_sets lowerCAmelCase__ = list(range(SCREAMING_SNAKE_CASE__ ) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> bool: lowerCAmelCase__ = self.get_parent(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_parent(SCREAMING_SNAKE_CASE__ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] lowerCAmelCase__ = 0 lowerCAmelCase__ = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 lowerCAmelCase__ = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] lowerCAmelCase__ = 0 lowerCAmelCase__ = src_parent lowerCAmelCase__ = self.set_counts[src_parent] lowerCAmelCase__ = max(self.max_set , SCREAMING_SNAKE_CASE__ ) return True def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: if self.parents[disj_set] == disj_set: return disj_set lowerCAmelCase__ = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
import numpy class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : numpy.ndarray , SCREAMING_SNAKE_CASE__ : numpy.ndarray ) -> None: lowerCAmelCase__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. lowerCAmelCase__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. lowerCAmelCase__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. lowerCAmelCase__ = numpy.random.rand(3 , 1 ) # Real output values provided. lowerCAmelCase__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. lowerCAmelCase__ = numpy.zeros(output_array.shape ) def a ( self : Union[str, Any] ) -> numpy.ndarray: lowerCAmelCase__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. lowerCAmelCase__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. lowerCAmelCase__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def a ( self : str ) -> None: lowerCAmelCase__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) lowerCAmelCase__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) lowerCAmelCase__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : numpy.ndarray , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool ) -> None: for iteration in range(1 , iterations + 1 ): lowerCAmelCase__ = self.feedforward() self.back_propagation() if give_loss: lowerCAmelCase__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'Iteration {iteration} Loss: {loss}' ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : numpy.ndarray ) -> int: lowerCAmelCase__ = input_arr lowerCAmelCase__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) lowerCAmelCase__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) lowerCAmelCase__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def _A ( lowerCAmelCase_ : numpy.ndarray ): """simple docstring""" return 1 / (1 + numpy.exp(-value )) def _A ( lowerCAmelCase_ : numpy.ndarray ): """simple docstring""" return (value) * (1 - (value)) def _A ( ): """simple docstring""" lowerCAmelCase__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. lowerCAmelCase__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. lowerCAmelCase__ = TwoHiddenLayerNeuralNetwork( input_array=lowerCAmelCase_ , output_array=lowerCAmelCase_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=lowerCAmelCase_ , iterations=10 , give_loss=lowerCAmelCase_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = AlbertTokenizer snake_case__ = AlbertTokenizerFast snake_case__ = True snake_case__ = True snake_case__ = True def a ( self : Union[str, Any] ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = AlbertTokenizer(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> int: lowerCAmelCase__ = "this is a test" lowerCAmelCase__ = "this is a test" return input_text, output_text def a ( self : Union[str, Any] ) -> Tuple: lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> List[str]: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "▁eloquent" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 30_000 ) def a ( self : Optional[int] ) -> int: self.assertEqual(self.get_tokenizer().vocab_size , 30_000 ) def a ( self : Any ) -> Dict: if not self.test_rust_tokenizer: return lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = "I was born in 92000, and this is falsé." lowerCAmelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Any ) -> Optional[int]: lowerCAmelCase__ = AlbertTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁this", "▁is", "▁a", "▁test"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [48, 25, 21, 1_289] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."] ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [31, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."] , ) def a ( self : Tuple ) -> int: lowerCAmelCase__ = AlbertTokenizer(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("sequence builders" ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def a ( self : Union[str, Any] ) -> Optional[Any]: # fmt: off lowerCAmelCase__ = {"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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "input_ids": [[2, 21_970, 13, 5, 6_092, 167, 28, 7_103, 2_153, 673, 8, 7_028, 12_051, 18, 17, 7_103, 2_153, 673, 8, 3_515, 18_684, 8, 4_461, 6, 1_927, 297, 8, 12_060, 2_607, 18, 13, 5, 4_461, 15, 10_538, 38, 8, 135, 15, 822, 58, 15, 993, 10_363, 15, 1_460, 8_005, 4_461, 15, 993, 255, 2_328, 9, 9, 9, 6, 26, 1_112, 816, 3_260, 13, 5, 103, 2_377, 6, 17, 1_112, 816, 2_782, 13, 5, 103, 10_641, 6, 29, 84, 2_512, 2_430, 782, 18_684, 2_761, 19, 808, 2_430, 2_556, 17, 855, 1_480, 9_477, 4_091, 128, 11_712, 15, 7_103, 2_153, 673, 17, 24_883, 9_990, 9, 3], [2, 11_502, 25, 1_006, 20, 782, 8, 11_809, 855, 1_732, 19_393, 18_667, 37, 367, 21_018, 69, 1_854, 34, 11_860, 19_124, 27, 156, 225, 17, 193, 4_141, 19, 65, 9_124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2_231, 886, 2_385, 17_659, 84, 14, 16_792, 1_952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="albert-base-v2" , revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e" , )
61
# 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : Dict , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) requires_backends(self , "vision" ) requires_backends(self , "torch" ) if self.framework != "pt": raise ValueError(f'The {self.__class__} is only available in PyTorch.' ) self.check_model_type(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = {} lowerCAmelCase__ = {} lowerCAmelCase__ = {} # preprocess args if "points_per_batch" in kwargs: lowerCAmelCase__ = kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCAmelCase__ = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCAmelCase__ = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCAmelCase__ = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCAmelCase__ = kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCAmelCase__ = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCAmelCase__ = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCAmelCase__ = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCAmelCase__ = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCAmelCase__ = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCAmelCase__ = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCAmelCase__ = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : Any , SCREAMING_SNAKE_CASE__ : str , *SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : str ) -> Dict: return super().__call__(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , num_workers=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any]=64 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : float = 512 / 1_500 , SCREAMING_SNAKE_CASE__ : Optional[int] = 32 , SCREAMING_SNAKE_CASE__ : Optional[int] = 1 , ) -> Union[str, Any]: lowerCAmelCase__ = load_image(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor.size["longest_edge"] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor.generate_crop_boxes( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) with self.device_placement(): if self.framework == "pt": lowerCAmelCase__ = self.get_inference_context() with inference_context(): lowerCAmelCase__ = self._ensure_tensor_on_device(SCREAMING_SNAKE_CASE__ , device=self.device ) lowerCAmelCase__ = self.model.get_image_embeddings(model_inputs.pop("pixel_values" ) ) lowerCAmelCase__ = image_embeddings lowerCAmelCase__ = grid_points.shape[1] lowerCAmelCase__ = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None" ) for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = grid_points[:, i : i + points_per_batch, :, :] lowerCAmelCase__ = input_labels[:, i : i + points_per_batch] lowerCAmelCase__ = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=0.88 , SCREAMING_SNAKE_CASE__ : List[Any]=0.95 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : str=1 , ) -> Tuple: lowerCAmelCase__ = model_inputs.pop("input_boxes" ) lowerCAmelCase__ = model_inputs.pop("is_last" ) lowerCAmelCase__ = model_inputs.pop("original_sizes" ).tolist() lowerCAmelCase__ = model_inputs.pop("reshaped_input_sizes" ).tolist() lowerCAmelCase__ = self.model(**SCREAMING_SNAKE_CASE__ ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCAmelCase__ = model_outputs["pred_masks"] lowerCAmelCase__ = self.image_processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , binarize=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model_outputs["iou_scores"] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Any=0.7 , ) -> List[Any]: lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = [] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores" ) ) all_masks.extend(model_output.pop("masks" ) ) all_boxes.append(model_output.pop("boxes" ) ) lowerCAmelCase__ = torch.cat(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.cat(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor.post_process_for_mask_generation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = defaultdict(SCREAMING_SNAKE_CASE__ ) for output in model_outputs: for k, v in output.items(): extra[k].append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = {} if output_rle_mask: lowerCAmelCase__ = rle_mask if output_bboxes_mask: lowerCAmelCase__ = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) UpperCamelCase = logging.getLogger(__name__) def _A ( ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser( description="Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)." ) parser.add_argument("--file_path" , type=lowerCAmelCase_ , default="data/dump.txt" , help="The path to the data." ) parser.add_argument("--tokenizer_type" , type=lowerCAmelCase_ , default="bert" , choices=["bert", "roberta", "gpt2"] ) parser.add_argument("--tokenizer_name" , type=lowerCAmelCase_ , default="bert-base-uncased" , help="The tokenizer to use." ) parser.add_argument("--dump_file" , type=lowerCAmelCase_ , default="data/dump" , help="The dump file prefix." ) lowerCAmelCase__ = parser.parse_args() logger.info(F'Loading Tokenizer ({args.tokenizer_name})' ) if args.tokenizer_type == "bert": lowerCAmelCase__ = BertTokenizer.from_pretrained(args.tokenizer_name ) lowerCAmelCase__ = tokenizer.special_tokens_map["cls_token"] # `[CLS]` lowerCAmelCase__ = tokenizer.special_tokens_map["sep_token"] # `[SEP]` elif args.tokenizer_type == "roberta": lowerCAmelCase__ = RobertaTokenizer.from_pretrained(args.tokenizer_name ) lowerCAmelCase__ = tokenizer.special_tokens_map["cls_token"] # `<s>` lowerCAmelCase__ = tokenizer.special_tokens_map["sep_token"] # `</s>` elif args.tokenizer_type == "gpt2": lowerCAmelCase__ = GPTaTokenizer.from_pretrained(args.tokenizer_name ) lowerCAmelCase__ = tokenizer.special_tokens_map["bos_token"] # `<|endoftext|>` lowerCAmelCase__ = tokenizer.special_tokens_map["eos_token"] # `<|endoftext|>` logger.info(F'Loading text from {args.file_path}' ) with open(args.file_path , "r" , encoding="utf8" ) as fp: lowerCAmelCase__ = fp.readlines() logger.info("Start encoding" ) logger.info(F'{len(lowerCAmelCase_ )} examples to process.' ) lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = 1_0000 lowerCAmelCase__ = time.time() for text in data: lowerCAmelCase__ = F'{bos} {text.strip()} {sep}' lowerCAmelCase__ = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) rslt.append(lowerCAmelCase_ ) iter += 1 if iter % interval == 0: lowerCAmelCase__ = time.time() logger.info(F'{iter} examples processed. - {(end-start):.2f}s/{interval}expl' ) lowerCAmelCase__ = time.time() logger.info("Finished binarization" ) logger.info(F'{len(lowerCAmelCase_ )} examples processed.' ) lowerCAmelCase__ = F'{args.dump_file}.{args.tokenizer_name}.pickle' lowerCAmelCase__ = tokenizer.vocab_size if vocab_size < (1 << 16): lowerCAmelCase__ = [np.uintaa(lowerCAmelCase_ ) for d in rslt] else: lowerCAmelCase__ = [np.intaa(lowerCAmelCase_ ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'Dump to {dp_file}' ) with open(lowerCAmelCase_ , "wb" ) as handle: pickle.dump(rslt_ , lowerCAmelCase_ , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = { 'configuration_trajectory_transformer': [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrajectoryTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrajectoryTransformerModel', 'TrajectoryTransformerPreTrainedModel', 'load_tf_weights_in_trajectory_transformer', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Union[str, Any] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a ( self : List[str] ) -> int: lowerCAmelCase__ = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler("sample_euler" ) lowerCAmelCase__ = "A painting of a squirrel eating a burger" lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler("sample_euler" ) lowerCAmelCase__ = "A painting of a squirrel eating a burger" lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def a ( self : Dict ) -> str: lowerCAmelCase__ = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler("sample_dpmpp_2m" ) lowerCAmelCase__ = "A painting of a squirrel eating a burger" lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=15 , output_type="np" , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline UpperCamelCase = version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11') def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : tuple , lowerCAmelCase_ : Path , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any]=False , ): """simple docstring""" output_path.parent.mkdir(parents=lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( lowerCAmelCase_ , lowerCAmelCase_ , f=output_path.as_posix() , input_names=lowerCAmelCase_ , output_names=lowerCAmelCase_ , dynamic_axes=lowerCAmelCase_ , do_constant_folding=lowerCAmelCase_ , use_external_data_format=lowerCAmelCase_ , enable_onnx_checker=lowerCAmelCase_ , opset_version=lowerCAmelCase_ , ) else: export( lowerCAmelCase_ , lowerCAmelCase_ , f=output_path.as_posix() , input_names=lowerCAmelCase_ , output_names=lowerCAmelCase_ , dynamic_axes=lowerCAmelCase_ , do_constant_folding=lowerCAmelCase_ , opset_version=lowerCAmelCase_ , ) @torch.no_grad() def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : int , lowerCAmelCase_ : bool = False ): """simple docstring""" lowerCAmelCase__ = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowerCAmelCase__ = "cuda" elif fpaa and not torch.cuda.is_available(): raise ValueError("`float16` model export is only supported on GPUs with CUDA" ) else: lowerCAmelCase__ = "cpu" lowerCAmelCase__ = StableDiffusionPipeline.from_pretrained(lowerCAmelCase_ , torch_dtype=lowerCAmelCase_ ).to(lowerCAmelCase_ ) lowerCAmelCase__ = Path(lowerCAmelCase_ ) # TEXT ENCODER lowerCAmelCase__ = pipeline.text_encoder.config.max_position_embeddings lowerCAmelCase__ = pipeline.text_encoder.config.hidden_size lowerCAmelCase__ = pipeline.tokenizer( "A sample prompt" , padding="max_length" , max_length=pipeline.tokenizer.model_max_length , truncation=lowerCAmelCase_ , return_tensors="pt" , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=lowerCAmelCase_ , dtype=torch.intaa )) , output_path=output_path / "text_encoder" / "model.onnx" , ordered_input_names=["input_ids"] , output_names=["last_hidden_state", "pooler_output"] , dynamic_axes={ "input_ids": {0: "batch", 1: "sequence"}, } , opset=lowerCAmelCase_ , ) del pipeline.text_encoder # UNET lowerCAmelCase__ = pipeline.unet.config.in_channels lowerCAmelCase__ = pipeline.unet.config.sample_size lowerCAmelCase__ = output_path / "unet" / "model.onnx" onnx_export( pipeline.unet , model_args=( torch.randn(2 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), torch.randn(2 ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), torch.randn(2 , lowerCAmelCase_ , lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), False, ) , output_path=lowerCAmelCase_ , ordered_input_names=["sample", "timestep", "encoder_hidden_states", "return_dict"] , output_names=["out_sample"] , dynamic_axes={ "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, "timestep": {0: "batch"}, "encoder_hidden_states": {0: "batch", 1: "sequence"}, } , opset=lowerCAmelCase_ , use_external_data_format=lowerCAmelCase_ , ) lowerCAmelCase__ = str(unet_path.absolute().as_posix() ) lowerCAmelCase__ = os.path.dirname(lowerCAmelCase_ ) lowerCAmelCase__ = onnx.load(lowerCAmelCase_ ) # clean up existing tensor files shutil.rmtree(lowerCAmelCase_ ) os.mkdir(lowerCAmelCase_ ) # collate external tensor files into one onnx.save_model( lowerCAmelCase_ , lowerCAmelCase_ , save_as_external_data=lowerCAmelCase_ , all_tensors_to_one_file=lowerCAmelCase_ , location="weights.pb" , convert_attribute=lowerCAmelCase_ , ) del pipeline.unet # VAE ENCODER lowerCAmelCase__ = pipeline.vae lowerCAmelCase__ = vae_encoder.config.in_channels lowerCAmelCase__ = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder lowerCAmelCase__ = lambda lowerCAmelCase_ , lowerCAmelCase_ : vae_encoder.encode(lowerCAmelCase_ , lowerCAmelCase_ )[0].sample() onnx_export( lowerCAmelCase_ , model_args=( torch.randn(1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), False, ) , output_path=output_path / "vae_encoder" / "model.onnx" , ordered_input_names=["sample", "return_dict"] , output_names=["latent_sample"] , dynamic_axes={ "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, } , opset=lowerCAmelCase_ , ) # VAE DECODER lowerCAmelCase__ = pipeline.vae lowerCAmelCase__ = vae_decoder.config.latent_channels lowerCAmelCase__ = vae_decoder.config.out_channels # forward only through the decoder part lowerCAmelCase__ = vae_encoder.decode onnx_export( lowerCAmelCase_ , model_args=( torch.randn(1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), False, ) , output_path=output_path / "vae_decoder" / "model.onnx" , ordered_input_names=["latent_sample", "return_dict"] , output_names=["sample"] , dynamic_axes={ "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, } , opset=lowerCAmelCase_ , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: lowerCAmelCase__ = pipeline.safety_checker lowerCAmelCase__ = safety_checker.config.vision_config.num_channels lowerCAmelCase__ = safety_checker.config.vision_config.image_size lowerCAmelCase__ = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), torch.randn(1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ), ) , output_path=output_path / "safety_checker" / "model.onnx" , ordered_input_names=["clip_input", "images"] , output_names=["out_images", "has_nsfw_concepts"] , dynamic_axes={ "clip_input": {0: "batch", 1: "channels", 2: "height", 3: "width"}, "images": {0: "batch", 1: "height", 2: "width", 3: "channels"}, } , opset=lowerCAmelCase_ , ) del pipeline.safety_checker lowerCAmelCase__ = OnnxRuntimeModel.from_pretrained(output_path / "safety_checker" ) lowerCAmelCase__ = pipeline.feature_extractor else: lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_encoder" ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_decoder" ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / "text_encoder" ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / "unet" ) , scheduler=pipeline.scheduler , safety_checker=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(lowerCAmelCase_ ) print("ONNX pipeline saved to" , lowerCAmelCase_ ) del pipeline del onnx_pipeline lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(lowerCAmelCase_ , provider="CPUExecutionProvider" ) print("ONNX pipeline is loadable" ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_path', type=str, required=True, help='Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).', ) parser.add_argument('--output_path', type=str, required=True, help='Path to the output model.') parser.add_argument( '--opset', default=14, type=int, help='The version of the ONNX operator set to use.', ) parser.add_argument('--fp16', action='store_true', default=False, help='Export the models in `float16` mode') UpperCamelCase = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter UpperCamelCase = True except ImportError: UpperCamelCase = False UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def _A ( lowerCAmelCase_ : Namespace ): """simple docstring""" return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" @staticmethod def a ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> int: lowerCAmelCase__ = parser.add_parser("add-new-model" ) add_new_model_parser.add_argument("--testing" , action="store_true" , help="If in testing mode." ) add_new_model_parser.add_argument("--testing_file" , type=SCREAMING_SNAKE_CASE__ , help="Configuration file on which to run." ) add_new_model_parser.add_argument( "--path" , type=SCREAMING_SNAKE_CASE__ , help="Path to cookiecutter. Should only be used for testing purposes." ) add_new_model_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , *SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: lowerCAmelCase__ = testing lowerCAmelCase__ = testing_file lowerCAmelCase__ = path def a ( self : Union[str, Any] ) -> Tuple: warnings.warn( "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. " "It is not actively maintained anymore, so might give a result that won't pass all tests and quality " "checks, you should use `transformers-cli add-new-model-like` instead." ) if not _has_cookiecutter: raise ImportError( "Model creation dependencies are required to use the `add_new_model` command. Install them by running " "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n" ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory lowerCAmelCase__ = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]] if len(SCREAMING_SNAKE_CASE__ ) > 0: raise ValueError( "Several directories starting with `cookiecutter-template-` in current working directory. " "Please clean your directory by removing all folders starting with `cookiecutter-template-` or " "change your working directory." ) lowerCAmelCase__ = ( Path(SCREAMING_SNAKE_CASE__ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) lowerCAmelCase__ = path_to_transformer_root / "templates" / "adding_a_new_model" # Execute cookiecutter if not self._testing: cookiecutter(str(SCREAMING_SNAKE_CASE__ ) ) else: with open(self._testing_file , "r" ) as configuration_file: lowerCAmelCase__ = json.load(SCREAMING_SNAKE_CASE__ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=SCREAMING_SNAKE_CASE__ , extra_context=SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0] # Retrieve configuration with open(directory + "/configuration.json" , "r" ) as configuration_file: lowerCAmelCase__ = json.load(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = configuration["lowercase_modelname"] lowerCAmelCase__ = configuration["generate_tensorflow_pytorch_and_flax"] os.remove(f'{directory}/configuration.json' ) lowerCAmelCase__ = "PyTorch" in generate_tensorflow_pytorch_and_flax lowerCAmelCase__ = "TensorFlow" in generate_tensorflow_pytorch_and_flax lowerCAmelCase__ = "Flax" in generate_tensorflow_pytorch_and_flax lowerCAmelCase__ = f'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) os.makedirs(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}' , exist_ok=SCREAMING_SNAKE_CASE__ ) # Tests require submodules as they have parent imports with open(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' , "w" ): pass shutil.move( f'{directory}/__init__.py' , f'{model_dir}/__init__.py' , ) shutil.move( f'{directory}/configuration_{lowercase_model_name}.py' , f'{model_dir}/configuration_{lowercase_model_name}.py' , ) def remove_copy_lines(SCREAMING_SNAKE_CASE__ : Dict ): with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: lowerCAmelCase__ = f.readlines() with open(SCREAMING_SNAKE_CASE__ , "w" ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(SCREAMING_SNAKE_CASE__ ) if output_pytorch: if not self._testing: remove_copy_lines(f'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_{lowercase_model_name}.py' , f'{model_dir}/modeling_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_tf_{lowercase_model_name}.py' , f'{model_dir}/modeling_tf_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_tf_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_flax_{lowercase_model_name}.py' , f'{model_dir}/modeling_flax_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_flax_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/{lowercase_model_name}.md' , f'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' , ) shutil.move( f'{directory}/tokenization_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/tokenization_fast_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}_fast.py' , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ): # Create temp file lowerCAmelCase__ , lowerCAmelCase__ = mkstemp() lowerCAmelCase__ = False with fdopen(SCREAMING_SNAKE_CASE__ , "w" ) as new_file: with open(SCREAMING_SNAKE_CASE__ ) as old_file: for line in old_file: new_file.write(SCREAMING_SNAKE_CASE__ ) if line_to_copy_below in line: lowerCAmelCase__ = True for line_to_copy in lines_to_copy: new_file.write(SCREAMING_SNAKE_CASE__ ) if not line_found: raise ValueError(f'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Remove original file remove(SCREAMING_SNAKE_CASE__ ) # Move new file move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def skip_units(SCREAMING_SNAKE_CASE__ : List[Any] ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ ) as datafile: lowerCAmelCase__ = [] lowerCAmelCase__ = False lowerCAmelCase__ = False for line in datafile: if "# To replace in: " in line and "##" not in line: lowerCAmelCase__ = line.split("\"" )[1] lowerCAmelCase__ = skip_units(SCREAMING_SNAKE_CASE__ ) elif "# Below: " in line and "##" not in line: lowerCAmelCase__ = line.split("\"" )[1] lowerCAmelCase__ = skip_units(SCREAMING_SNAKE_CASE__ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = [] elif "# Replace with" in line and "##" not in line: lowerCAmelCase__ = [] elif "##" not in line: lines_to_copy.append(SCREAMING_SNAKE_CASE__ ) remove(SCREAMING_SNAKE_CASE__ ) replace_in_files(f'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(SCREAMING_SNAKE_CASE__ )
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _A ( ): """simple docstring""" raise RuntimeError("CUDA out of memory." ) class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self : Any ) -> str: super().__init__() lowerCAmelCase__ = nn.Linear(3 , 4 ) lowerCAmelCase__ = nn.BatchNormad(4 ) lowerCAmelCase__ = nn.Linear(4 , 5 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> int: return self.lineara(self.batchnorm(self.lineara(SCREAMING_SNAKE_CASE__ ) ) ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): nonlocal batch_sizes batch_sizes.append(SCREAMING_SNAKE_CASE__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(SCREAMING_SNAKE_CASE__ , [128, 64, 32, 16, 8] ) def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): nonlocal batch_sizes batch_sizes.append(SCREAMING_SNAKE_CASE__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga lowerCAmelCase__ , lowerCAmelCase__ = mock_training_loop_function("hello" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, "hello"] ) def a ( self : Union[str, Any] ) -> Any: @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : List[Any] ): pass with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def a ( self : List[str] ) -> Any: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : str ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def a ( self : Dict ) -> Union[str, Any]: @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function(128 , "hello" , "world" ) self.assertIn("Batch size was passed into `f`" , cm.exception.args[0] ) self.assertIn("`f(arg1='hello', arg2='world')" , cm.exception.args[0] ) def a ( self : Optional[Any] ) -> List[Any]: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : List[Any] ): raise ValueError("Oops, we had an error!" ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn("Oops, we had an error!" , cm.exception.args[0] ) @require_cuda def a ( self : Optional[Any] ) -> List[str]: lowerCAmelCase__ = torch.cuda.memory_allocated() lowerCAmelCase__ = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = release_memory(SCREAMING_SNAKE_CASE__ ) self.assertEqual(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ )
61
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
1
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask UpperCamelCase = logging.getLogger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int=-1 ) -> List[Any]: # in NER datasets, the last column is usually reserved for NER label lowerCAmelCase__ = label_idx def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = mode.value lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , f'{mode}.txt' ) lowerCAmelCase__ = 1 lowerCAmelCase__ = [] with open(SCREAMING_SNAKE_CASE__ , encoding="utf-8" ) as f: lowerCAmelCase__ = [] lowerCAmelCase__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) ) guid_index += 1 lowerCAmelCase__ = [] lowerCAmelCase__ = [] else: lowerCAmelCase__ = line.split(" " ) words.append(splits[0] ) if len(SCREAMING_SNAKE_CASE__ ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) ) return examples def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : TextIO , SCREAMING_SNAKE_CASE__ : TextIO , SCREAMING_SNAKE_CASE__ : List ) -> str: lowerCAmelCase__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(SCREAMING_SNAKE_CASE__ ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(SCREAMING_SNAKE_CASE__ ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def a ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: if path: with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: lowerCAmelCase__ = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : int ) -> Optional[int]: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: if path: with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: lowerCAmelCase__ = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def a ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = mode.value lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , f'{mode}.txt' ) lowerCAmelCase__ = 1 lowerCAmelCase__ = [] with open(SCREAMING_SNAKE_CASE__ , encoding="utf-8" ) as f: for sentence in parse_incr(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) ) guid_index += 1 return examples def a ( self : Dict , SCREAMING_SNAKE_CASE__ : TextIO , SCREAMING_SNAKE_CASE__ : TextIO , SCREAMING_SNAKE_CASE__ : List ) -> Optional[Any]: lowerCAmelCase__ = 0 for sentence in parse_incr(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = preds_list[example_id] lowerCAmelCase__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(SCREAMING_SNAKE_CASE__ ) example_id += 1 def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: if path: with open(SCREAMING_SNAKE_CASE__ , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
UpperCamelCase = range(2, 20 + 1) UpperCamelCase = [10**k for k in range(ks[-1] + 1)] UpperCamelCase = {} def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = sum(a_i[j] for j in range(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = sum(a_i[j] * base[j] for j in range(min(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) ) ) lowerCAmelCase__ , lowerCAmelCase__ = 0, 0 lowerCAmelCase__ = n - i lowerCAmelCase__ = memo.get(lowerCAmelCase_ ) if sub_memo is not None: lowerCAmelCase__ = sub_memo.get(lowerCAmelCase_ ) if jumps is not None and len(lowerCAmelCase_ ) > 0: # find and make the largest jump without going over lowerCAmelCase__ = -1 for _k in range(len(lowerCAmelCase_ ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: lowerCAmelCase__ = _k break if max_jump >= 0: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = jumps[max_jump] # since the difference between jumps is cached, add c lowerCAmelCase__ = diff + c for j in range(min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) ): lowerCAmelCase__ , lowerCAmelCase__ = divmod(lowerCAmelCase_ , 10 ) if new_c > 0: add(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) else: lowerCAmelCase__ = [] else: lowerCAmelCase__ = {c: []} lowerCAmelCase__ = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps lowerCAmelCase__ , lowerCAmelCase__ = next_term(lowerCAmelCase_ , k - 1 , i + dn , lowerCAmelCase_ ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead lowerCAmelCase__ , lowerCAmelCase__ = compute(lowerCAmelCase_ , lowerCAmelCase_ , i + dn , lowerCAmelCase_ ) diff += _diff dn += terms_jumped lowerCAmelCase__ = sub_memo[c] # keep jumps sorted by # of terms skipped lowerCAmelCase__ = 0 while j < len(lowerCAmelCase_ ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(lowerCAmelCase_ , (diff, dn, k) ) return (diff, dn) def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if i >= n: return 0, i if k > len(lowerCAmelCase_ ): a_i.extend([0 for _ in range(k - len(lowerCAmelCase_ ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) lowerCAmelCase__ = i lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 0, 0, 0 for j in range(len(lowerCAmelCase_ ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 lowerCAmelCase__ = ds_c + ds_b diff += addend lowerCAmelCase__ = 0 for j in range(lowerCAmelCase_ ): lowerCAmelCase__ = a_i[j] + addend lowerCAmelCase__ , lowerCAmelCase__ = divmod(lowerCAmelCase_ , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return diff, i - start_i def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] ): """simple docstring""" for j in range(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): lowerCAmelCase__ = digits[j] + addend if s >= 10: lowerCAmelCase__ , lowerCAmelCase__ = divmod(lowerCAmelCase_ , 10 ) lowerCAmelCase__ = addend // 10 + quotient else: lowerCAmelCase__ = s lowerCAmelCase__ = addend // 10 if addend == 0: break while addend > 0: lowerCAmelCase__ , lowerCAmelCase__ = divmod(lowerCAmelCase_ , 10 ) digits.append(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : int = 10**15 ): """simple docstring""" lowerCAmelCase__ = [1] lowerCAmelCase__ = 1 lowerCAmelCase__ = 0 while True: lowerCAmelCase__ , lowerCAmelCase__ = next_term(lowerCAmelCase_ , 20 , i + dn , lowerCAmelCase_ ) dn += terms_jumped if dn == n - i: break lowerCAmelCase__ = 0 for j in range(len(lowerCAmelCase_ ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(F"""{solution() = }""")
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function UpperCamelCase = 1.0_5457_1817E-34 # unit of ℏ : J * s UpperCamelCase = 3E8 # unit of c : m * s^-1 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if force < 0: raise ValueError("Magnitude of force can not be negative" ) if distance < 0: raise ValueError("Distance can not be negative" ) if area < 0: raise ValueError("Area can not be negative" ) if force == 0: lowerCAmelCase__ = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: lowerCAmelCase__ = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: lowerCAmelCase__ = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
def _A ( lowerCAmelCase_ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = [0] * len(lowerCAmelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [1] * len(lowerCAmelCase_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase_ ) ): if indegree[i] == 0: queue.append(lowerCAmelCase_ ) while queue: lowerCAmelCase__ = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowerCAmelCase__ = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase_ ) print(max(lowerCAmelCase_ ) ) # Adjacency list of Graph UpperCamelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class __lowerCamelCase : """simple docstring""" def __init__( self : int , SCREAMING_SNAKE_CASE__ : Collection[float] | None = None ) -> None: if components is None: lowerCAmelCase__ = [] lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE__ ) def __len__( self : Tuple ) -> int: return len(self.__components ) def __str__( self : List[Any] ) -> str: return "(" + ",".join(map(SCREAMING_SNAKE_CASE__ , self.__components ) ) + ")" def __add__( self : Tuple , SCREAMING_SNAKE_CASE__ : Vector ) -> Vector: lowerCAmelCase__ = len(self ) if size == len(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [self.__components[i] + other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) else: raise Exception("must have the same size" ) def __sub__( self : str , SCREAMING_SNAKE_CASE__ : Vector ) -> Vector: lowerCAmelCase__ = len(self ) if size == len(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [self.__components[i] - other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self : List[str] , SCREAMING_SNAKE_CASE__ : float ) -> Vector: ... @overload def __mul__( self : Dict , SCREAMING_SNAKE_CASE__ : Vector ) -> float: ... def __mul__( self : int , SCREAMING_SNAKE_CASE__ : float | Vector ) -> float | Vector: if isinstance(SCREAMING_SNAKE_CASE__ , (float, int) ): lowerCAmelCase__ = [c * other for c in self.__components] return Vector(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(self ) == len(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = len(self ) lowerCAmelCase__ = [self.__components[i] * other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return sum(SCREAMING_SNAKE_CASE__ ) else: # error case raise Exception("invalid operand!" ) def a ( self : Optional[int] ) -> Vector: return Vector(self.__components ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> float: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def a ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) lowerCAmelCase__ = value def a ( self : Tuple ) -> float: if len(self.__components ) == 0: raise Exception("Vector is empty" ) lowerCAmelCase__ = [c**2 for c in self.__components] return math.sqrt(sum(SCREAMING_SNAKE_CASE__ ) ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : bool = False ) -> float: lowerCAmelCase__ = self * other lowerCAmelCase__ = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) return Vector([0] * dimension ) def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , lowerCAmelCase_ )) lowerCAmelCase__ = [0] * dimension lowerCAmelCase__ = 1 return Vector(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : Vector , lowerCAmelCase_ : Vector ): """simple docstring""" assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , (int, float) )) ) return x * scalar + y def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" random.seed(lowerCAmelCase_ ) lowerCAmelCase__ = [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] return Vector(lowerCAmelCase_ ) class __lowerCamelCase : """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : list[list[float]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = matrix lowerCAmelCase__ = w lowerCAmelCase__ = h def __str__( self : List[str] ) -> str: lowerCAmelCase__ = "" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Matrix ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): lowerCAmelCase__ = [] for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] + other.component(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] matrix.append(SCREAMING_SNAKE_CASE__ ) return Matrix(SCREAMING_SNAKE_CASE__ , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Matrix ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): lowerCAmelCase__ = [] for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] - other.component(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] matrix.append(SCREAMING_SNAKE_CASE__ ) return Matrix(SCREAMING_SNAKE_CASE__ , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : float ) -> Matrix: ... @overload def __mul__( self : Tuple , SCREAMING_SNAKE_CASE__ : Vector ) -> Vector: ... def __mul__( self : List[Any] , SCREAMING_SNAKE_CASE__ : float | Vector ) -> Vector | Matrix: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # matrix-vector if len(SCREAMING_SNAKE_CASE__ ) == self.__width: lowerCAmelCase__ = zero_vector(self.__height ) for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] * other.component(SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] ans.change_component(SCREAMING_SNAKE_CASE__ , sum(SCREAMING_SNAKE_CASE__ ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float) ): # matrix-scalar lowerCAmelCase__ = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(SCREAMING_SNAKE_CASE__ , self.__width , self.__height ) return None def a ( self : Dict ) -> int: return self.__height def a ( self : Dict ) -> int: return self.__width def a ( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: lowerCAmelCase__ = value else: raise Exception("change_component: indices out of bounds" ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: if self.__height != self.__width: raise Exception("Matrix is not square" ) lowerCAmelCase__ = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): lowerCAmelCase__ = minor[i][:y] + minor[i][y + 1 :] return Matrix(SCREAMING_SNAKE_CASE__ , self.__width - 1 , self.__height - 1 ).determinant() def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: raise Exception("Indices out of bounds" ) def a ( self : Any ) -> float: if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: lowerCAmelCase__ = [ self.__matrix[0][y] * self.cofactor(0 , SCREAMING_SNAKE_CASE__ ) for y in range(self.__width ) ] return sum(SCREAMING_SNAKE_CASE__ ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [[0] * n for _ in range(lowerCAmelCase_ )] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" random.seed(lowerCAmelCase_ ) lowerCAmelCase__ = [ [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] for _ in range(lowerCAmelCase_ ) ] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
1
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel UpperCamelCase = { 'text_branch': 'text_model', 'audio_branch': 'audio_model.audio_encoder', 'attn': 'attention.self', 'self.proj': 'output.dense', 'attention.self_mask': 'attn_mask', 'mlp.fc1': 'intermediate.dense', 'mlp.fc2': 'output.dense', 'norm1': 'layernorm_before', 'norm2': 'layernorm_after', 'bn0': 'batch_norm', } UpperCamelCase = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc') def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str=False ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ = create_model( "HTSAT-tiny" , "roberta" , lowerCAmelCase_ , precision="fp32" , device="cuda:0" if torch.cuda.is_available() else "cpu" , enable_fusion=lowerCAmelCase_ , fusion_type="aff_2d" if enable_fusion else None , ) return model, model_cfg def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = {} lowerCAmelCase__ = r".*sequential.(\d+).*" lowerCAmelCase__ = r".*_projection.(\d+).*" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: lowerCAmelCase__ = key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if re.match(lowerCAmelCase_ , lowerCAmelCase_ ): # replace sequential layers with list lowerCAmelCase__ = re.match(lowerCAmelCase_ , lowerCAmelCase_ ).group(1 ) lowerCAmelCase__ = key.replace(F'sequential.{sequential_layer}.' , F'layers.{int(lowerCAmelCase_ )//3}.linear.' ) elif re.match(lowerCAmelCase_ , lowerCAmelCase_ ): lowerCAmelCase__ = int(re.match(lowerCAmelCase_ , lowerCAmelCase_ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... lowerCAmelCase__ = 1 if projecton_layer == 0 else 2 lowerCAmelCase__ = key.replace(F'_projection.{projecton_layer}.' , F'_projection.linear{transformers_projection_layer}.' ) if "audio" and "qkv" in key: # split qkv into query key and value lowerCAmelCase__ = value lowerCAmelCase__ = mixed_qkv.size(0 ) // 3 lowerCAmelCase__ = mixed_qkv[:qkv_dim] lowerCAmelCase__ = mixed_qkv[qkv_dim : qkv_dim * 2] lowerCAmelCase__ = mixed_qkv[qkv_dim * 2 :] lowerCAmelCase__ = query_layer lowerCAmelCase__ = key_layer lowerCAmelCase__ = value_layer else: lowerCAmelCase__ = value return model_state_dict def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : str=False ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ = init_clap(lowerCAmelCase_ , enable_fusion=lowerCAmelCase_ ) clap_model.eval() lowerCAmelCase__ = clap_model.state_dict() lowerCAmelCase__ = rename_state_dict(lowerCAmelCase_ ) lowerCAmelCase__ = ClapConfig() lowerCAmelCase__ = enable_fusion lowerCAmelCase__ = ClapModel(lowerCAmelCase_ ) # ignore the spectrogram embedding layer model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) transformers_config.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = 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') parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not') UpperCamelCase = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def _A ( lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ = emb.weight.shape lowerCAmelCase__ = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) lowerCAmelCase__ = emb.weight.data return lin_layer def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict=None ): """simple docstring""" lowerCAmelCase__ = {} for old_key in state_dict.keys(): lowerCAmelCase__ = old_key if "moe_layer.experts." in key: if expert_idx is not None: lowerCAmelCase__ = key.replace("moe_layer.experts.0" , F'ffn.experts.expert_{expert_idx}' ) else: lowerCAmelCase__ = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: lowerCAmelCase__ = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: lowerCAmelCase__ = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: lowerCAmelCase__ = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: lowerCAmelCase__ = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: lowerCAmelCase__ = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: lowerCAmelCase__ = key.replace("final_layer_norm" , "ff_layer_norm" ) lowerCAmelCase__ = state_dict[old_key] return new_dict def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str = WEIGHTS_NAME ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = 0 os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) for expert in range(lowerCAmelCase_ ): lowerCAmelCase__ = switch_checkpoint_path + F'-rank-{expert}.pt' if os.path.isfile(lowerCAmelCase_ ): lowerCAmelCase__ = torch.load(lowerCAmelCase_ )["model"] remove_ignore_keys_(lowerCAmelCase_ ) lowerCAmelCase__ = rename_fairseq_keys(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join( lowerCAmelCase_ , weights_name.replace(".bin" , F'-{len(lowerCAmelCase_ )+1:05d}-of-???.bin' ) ) torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(lowerCAmelCase_ )[0]].dtype ) # Add the last block lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , weights_name.replace(".bin" , F'-{len(lowerCAmelCase_ )+1:05d}-of-???.bin' ) ) lowerCAmelCase__ = torch.load(switch_checkpoint_path + "-shared.pt" )["model"] remove_ignore_keys_(lowerCAmelCase_ ) lowerCAmelCase__ = rename_fairseq_keys(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(lowerCAmelCase_ ) == 1: lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) # Otherwise, let's build the index lowerCAmelCase__ = {} for idx, shard in enumerate(lowerCAmelCase_ ): lowerCAmelCase__ = weights_name.replace(".bin" , F'-{idx+1:05d}-of-{len(lowerCAmelCase_ ):05d}.bin' ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , weights_name.replace(".bin" , F'-{idx+1:05d}-of-???.bin' ) ) os.rename(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) ) for key in shard: lowerCAmelCase__ = shard_file # Add the metadata lowerCAmelCase__ = {"total_size": total_size} lowerCAmelCase__ = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , "w" , encoding="utf-8" ) as f: lowerCAmelCase__ = json.dumps(lowerCAmelCase_ , indent=2 , sort_keys=lowerCAmelCase_ ) + "\n" f.write(lowerCAmelCase_ ) return metadata, index if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) UpperCamelCase = parser.parse_args() UpperCamelCase , UpperCamelCase = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) UpperCamelCase = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) UpperCamelCase = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> None: warnings.warn( "The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use PerceiverImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 class __lowerCamelCase ( nn.Module ): """simple docstring""" snake_case__ = 42 snake_case__ = (1_6, 3_2, 9_6, 2_5_6) snake_case__ = jnp.floataa def a ( self : Any ) -> Dict: lowerCAmelCase__ = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowerCAmelCase__ = [] for i in range(len(self.block_out_channels ) - 1 ): lowerCAmelCase__ = self.block_out_channels[i] lowerCAmelCase__ = self.block_out_channels[i + 1] lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = blocks lowerCAmelCase__ = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: lowerCAmelCase__ = self.conv_in(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = nn.silu(SCREAMING_SNAKE_CASE__ ) for block in self.blocks: lowerCAmelCase__ = block(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = nn.silu(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.conv_out(SCREAMING_SNAKE_CASE__ ) return embedding @flax_register_to_config class __lowerCamelCase ( nn.Module , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" snake_case__ = 3_2 snake_case__ = 4 snake_case__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) snake_case__ = False snake_case__ = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) snake_case__ = 2 snake_case__ = 8 snake_case__ = None snake_case__ = 1_2_8_0 snake_case__ = 0.0 snake_case__ = False snake_case__ = jnp.floataa snake_case__ = True snake_case__ = 0 snake_case__ = "rgb" snake_case__ = (1_6, 3_2, 9_6, 2_5_6) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : jax.random.KeyArray ) -> FrozenDict: # init input tensors lowerCAmelCase__ = (1, self.in_channels, self.sample_size, self.sample_size) lowerCAmelCase__ = jnp.zeros(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) lowerCAmelCase__ = jnp.ones((1,) , dtype=jnp.intaa ) lowerCAmelCase__ = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowerCAmelCase__ = (1, 3, self.sample_size * 8, self.sample_size * 8) lowerCAmelCase__ = jnp.zeros(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) lowerCAmelCase__ , lowerCAmelCase__ = jax.random.split(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = {"params": params_rng, "dropout": dropout_rng} return self.init(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )["params"] def a ( self : List[str] ) -> Optional[Any]: lowerCAmelCase__ = self.block_out_channels lowerCAmelCase__ = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowerCAmelCase__ = self.num_attention_heads or self.attention_head_dim # input lowerCAmelCase__ = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowerCAmelCase__ = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowerCAmelCase__ = FlaxTimestepEmbedding(SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) lowerCAmelCase__ = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowerCAmelCase__ = self.only_cross_attention if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = (only_cross_attention,) * len(self.down_block_types ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = (num_attention_heads,) * len(self.down_block_types ) # down lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = block_out_channels[0] lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE__ ) for i, down_block_type in enumerate(self.down_block_types ): lowerCAmelCase__ = output_channel lowerCAmelCase__ = block_out_channels[i] lowerCAmelCase__ = i == len(SCREAMING_SNAKE_CASE__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowerCAmelCase__ = FlaxCrossAttnDownBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=SCREAMING_SNAKE_CASE__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowerCAmelCase__ = FlaxDownBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=SCREAMING_SNAKE_CASE__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(SCREAMING_SNAKE_CASE__ ) for _ in range(self.layers_per_block ): lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE__ ) if not is_final_block: lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = down_blocks lowerCAmelCase__ = controlnet_down_blocks # mid lowerCAmelCase__ = block_out_channels[-1] lowerCAmelCase__ = FlaxUNetMidBlockaDCrossAttn( in_channels=SCREAMING_SNAKE_CASE__ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowerCAmelCase__ = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Union[FlaxControlNetOutput, Tuple]: lowerCAmelCase__ = self.controlnet_conditioning_channel_order if channel_order == "bgr": lowerCAmelCase__ = jnp.flip(SCREAMING_SNAKE_CASE__ , axis=1 ) # 1. time if not isinstance(SCREAMING_SNAKE_CASE__ , jnp.ndarray ): lowerCAmelCase__ = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(SCREAMING_SNAKE_CASE__ , jnp.ndarray ) and len(timesteps.shape ) == 0: lowerCAmelCase__ = timesteps.astype(dtype=jnp.floataa ) lowerCAmelCase__ = jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 0 ) lowerCAmelCase__ = self.time_proj(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.time_embedding(SCREAMING_SNAKE_CASE__ ) # 2. pre-process lowerCAmelCase__ = jnp.transpose(SCREAMING_SNAKE_CASE__ , (0, 2, 3, 1) ) lowerCAmelCase__ = self.conv_in(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = jnp.transpose(SCREAMING_SNAKE_CASE__ , (0, 2, 3, 1) ) lowerCAmelCase__ = self.controlnet_cond_embedding(SCREAMING_SNAKE_CASE__ ) sample += controlnet_cond # 3. down lowerCAmelCase__ = (sample,) for down_block in self.down_blocks: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ , lowerCAmelCase__ = down_block(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=not train ) else: lowerCAmelCase__ , lowerCAmelCase__ = down_block(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowerCAmelCase__ = self.mid_block(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=not train ) # 5. contronet blocks lowerCAmelCase__ = () for down_block_res_sample, controlnet_block in zip(SCREAMING_SNAKE_CASE__ , self.controlnet_down_blocks ): lowerCAmelCase__ = controlnet_block(SCREAMING_SNAKE_CASE__ ) controlnet_down_block_res_samples += (down_block_res_sample,) lowerCAmelCase__ = controlnet_down_block_res_samples lowerCAmelCase__ = self.controlnet_mid_block(SCREAMING_SNAKE_CASE__ ) # 6. scaling lowerCAmelCase__ = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=SCREAMING_SNAKE_CASE__ , mid_block_res_sample=SCREAMING_SNAKE_CASE__ )
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCamelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Any , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 224} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 224, "width": 224} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ , param_name="crop_size" ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCAmelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD lowerCAmelCase__ = do_convert_rgb def a ( self : Any , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size["shortest_edge"] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Any , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size["height"], size["width"]) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : int = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name="size" , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCAmelCase__ = crop_size if crop_size is not None else self.crop_size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name="crop_size" , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCAmelCase__ = [convert_to_rgb(SCREAMING_SNAKE_CASE__ ) for image in images] # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: lowerCAmelCase__ = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "timm_backbone" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = backbone lowerCAmelCase__ = num_channels lowerCAmelCase__ = features_only lowerCAmelCase__ = use_pretrained_backbone lowerCAmelCase__ = True lowerCAmelCase__ = out_indices if out_indices is not None else (-1,)
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
UpperCamelCase = {str(digit): digit**5 for digit in range(10)} def _A ( lowerCAmelCase_ : int ): """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(lowerCAmelCase_ ) ) def _A ( ): """simple docstring""" return sum( number for number in range(1000 , 100_0000 ) if number == digits_fifth_powers_sum(lowerCAmelCase_ ) ) if __name__ == "__main__": print(solution())
61
# 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = Mock() lowerCAmelCase__ = conn, Mock() lowerCAmelCase__ = iter([1, None] ) lowerCAmelCase__ = lambda lowerCAmelCase_ : next(lowerCAmelCase_ ) # ===== invoke ===== send_file(filename="mytext.txt" , testing=lowerCAmelCase_ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=7 , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=18 , SCREAMING_SNAKE_CASE__ : List[str]=30 , SCREAMING_SNAKE_CASE__ : Dict=400 , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=[0.48_145_466, 0.4_578_275, 0.40_821_073] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , ) -> int: lowerCAmelCase__ = size if size is not None else {"height": 224, "width": 224} lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 18, "width": 18} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean lowerCAmelCase__ = image_std lowerCAmelCase__ = do_convert_rgb def a ( self : Union[str, Any] ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Optional[Any]: assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: lowerCAmelCase__ = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: lowerCAmelCase__ = [] for i in range(self.batch_size ): lowerCAmelCase__ , lowerCAmelCase__ = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension lowerCAmelCase__ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] if torchify: lowerCAmelCase__ = [torch.from_numpy(SCREAMING_SNAKE_CASE__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = ChineseCLIPImageProcessor if is_vision_available() else None def a ( self : Optional[Any] ) -> List[str]: lowerCAmelCase__ = ChineseCLIPImageProcessingTester(self , do_center_crop=SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def a ( self : Tuple ) -> int: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_center_crop" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "center_crop" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_normalize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_mean" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_std" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_convert_rgb" ) ) def a ( self : Dict ) -> int: lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) lowerCAmelCase__ = 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 : str ) -> Optional[int]: pass def a ( self : Tuple ) -> Union[str, Any]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input lowerCAmelCase__ = 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__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 : Union[str, Any] ) -> Dict: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = 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__ = image_processing(SCREAMING_SNAKE_CASE__ , 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 : Optional[Any] ) -> Any: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = 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__ = image_processing(SCREAMING_SNAKE_CASE__ , 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"], ) , ) @require_torch @require_vision class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = ChineseCLIPImageProcessor if is_vision_available() else None def a ( self : Optional[int] ) -> Union[str, Any]: lowerCAmelCase__ = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 3 @property def a ( self : int ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_center_crop" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "center_crop" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_normalize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_mean" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_std" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_convert_rgb" ) ) def a ( self : Any ) -> Optional[int]: pass def a ( self : str ) -> Union[str, Any]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "tokenizer"] snake_case__ = "LayoutLMv2ImageProcessor" snake_case__ = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , SCREAMING_SNAKE_CASE__ : Union[List[List[int]], List[List[List[int]]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[List[int], List[List[int]]]] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> BatchEncoding: # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor lowerCAmelCase__ = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [text] # add batch dimension (as the image processor always adds a batch dimension) lowerCAmelCase__ = features["words"] lowerCAmelCase__ = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # add pixel values lowerCAmelCase__ = features.pop("pixel_values" ) if return_overflowing_tokens is True: lowerCAmelCase__ = self.get_overflowing_images(SCREAMING_SNAKE_CASE__ , encoded_inputs["overflow_to_sample_mapping"] ) lowerCAmelCase__ = images return encoded_inputs def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image lowerCAmelCase__ = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(SCREAMING_SNAKE_CASE__ )} and {len(SCREAMING_SNAKE_CASE__ )}' ) return images_with_overflow def a ( self : int , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def a ( self : Any ) -> Optional[Any]: return ["input_ids", "bbox", "attention_mask", "image"] @property def a ( self : Union[str, Any] ) -> int: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def a ( self : List[str] ) -> Tuple: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "gpt_neo" snake_case__ = ["past_key_values"] snake_case__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : int , SCREAMING_SNAKE_CASE__ : Any=50_257 , SCREAMING_SNAKE_CASE__ : Any=2_048 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2_048 , SCREAMING_SNAKE_CASE__ : int=24 , SCREAMING_SNAKE_CASE__ : Tuple=[[["global", "local"], 12]] , SCREAMING_SNAKE_CASE__ : str=16 , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=256 , SCREAMING_SNAKE_CASE__ : Any="gelu_new" , SCREAMING_SNAKE_CASE__ : List[str]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=1e-5 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Dict=50_256 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=50_256 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[str]: lowerCAmelCase__ = vocab_size lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_layers lowerCAmelCase__ = num_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = window_size lowerCAmelCase__ = activation_function lowerCAmelCase__ = resid_dropout lowerCAmelCase__ = embed_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = classifier_dropout lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_range lowerCAmelCase__ = use_cache lowerCAmelCase__ = bos_token_id lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = attention_types lowerCAmelCase__ = self.expand_attention_types_params(SCREAMING_SNAKE_CASE__ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f'but is `len(config.attention_layers) = {len(self.attention_layers )}`, ' f'`config.num_layers = {self.num_layers}`. ' "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : List[str] ) -> List[Any]: lowerCAmelCase__ = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" import torch lowerCAmelCase__ = input.size() lowerCAmelCase__ = len(lowerCAmelCase_ ) lowerCAmelCase__ = shape[dimension] lowerCAmelCase__ = torch.arange(0 , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = torch.div(sizedim - size , lowerCAmelCase_ , rounding_mode="floor" ) + 1 lowerCAmelCase__ = torch.arange(lowerCAmelCase_ ) + low_indices[:min_length][:, None] lowerCAmelCase__ = [slice(lowerCAmelCase_ )] * rank lowerCAmelCase__ = indices lowerCAmelCase__ = input[s] lowerCAmelCase__ = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple ): """simple docstring""" import torch lowerCAmelCase__ = torch.arange(1 , lowerCAmelCase_ ) lowerCAmelCase__ = torch.remainder(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = remainders == 0 lowerCAmelCase__ = candidates[divisor_indices] lowerCAmelCase__ = torch.max(lowerCAmelCase_ ) return largest_divisor, torch.div(lowerCAmelCase_ , lowerCAmelCase_ , rounding_mode="floor" ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" @property def a ( self : str ) -> Mapping[str, Mapping[int, str]]: lowerCAmelCase__ = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ , direction="inputs" ) lowerCAmelCase__ = {0: "batch", 1: "past_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "sequence"} return common_inputs @property def a ( self : List[str] ) -> int: return self._config.num_heads def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: lowerCAmelCase__ = super(SCREAMING_SNAKE_CASE__ , self ).generate_dummy_inputs( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) # We need to order the input in the way they appears in the forward() lowerCAmelCase__ = 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__ = common_inputs["input_ids"].shape # Not using the same length for past_key_values lowerCAmelCase__ = seqlen + 2 lowerCAmelCase__ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCAmelCase__ = [ (torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ )) for _ in range(self.num_layers ) ] lowerCAmelCase__ = common_inputs["attention_mask"] if self.use_past: lowerCAmelCase__ = ordered_inputs["attention_mask"].dtype lowerCAmelCase__ = torch.cat( [ordered_inputs["attention_mask"], torch.ones(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )] , dim=1 ) return ordered_inputs @property def a ( self : str ) -> int: return 13
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
# 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
import sys UpperCamelCase = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _A ( lowerCAmelCase_ : str = N ): """simple docstring""" lowerCAmelCase__ = -sys.maxsize - 1 for i in range(len(lowerCAmelCase_ ) - 12 ): lowerCAmelCase__ = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowerCAmelCase__ = product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
from __future__ import annotations import math def _A ( lowerCAmelCase_ : int ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True UpperCamelCase = [num for num in range(3, 10_0001, 2) if not is_prime(num)] def _A ( lowerCAmelCase_ : int ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("n must be an integer" ) if n <= 0: raise ValueError("n must be >= 0" ) lowerCAmelCase__ = [] for num in range(len(lowerCAmelCase_ ) ): lowerCAmelCase__ = 0 while 2 * i * i <= odd_composites[num]: lowerCAmelCase__ = odd_composites[num] - 2 * i * i if is_prime(lowerCAmelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCAmelCase_ ) == n: return list_nums return [] def _A ( ): """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F"""{solution() = }""")
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import functools def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = len(lowerCAmelCase_ ) lowerCAmelCase__ = len(lowerCAmelCase_ ) @functools.cache def min_distance(lowerCAmelCase_ : int , lowerCAmelCase_ : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa lowerCAmelCase__ = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , lowerCAmelCase_ ) , 1 + min_distance(lowerCAmelCase_ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
61
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
1
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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'facebook/deit-base-distilled-patch16-224': ( 'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "deit" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=768 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : str=1e-1_2 , SCREAMING_SNAKE_CASE__ : int=224 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : List[str]=16 , **SCREAMING_SNAKE_CASE__ : Any , ) -> str: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias lowerCAmelCase__ = encoder_stride class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = version.parse("1.11" ) @property def a ( self : Any ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def a ( self : Dict ) -> float: return 1e-4
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} UpperCamelCase = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } UpperCamelCase = { 'squeezebert/squeezebert-uncased': 512, 'squeezebert/squeezebert-mnli': 512, 'squeezebert/squeezebert-mnli-headless': 512, } UpperCamelCase = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_INIT_CONFIGURATION snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = SqueezeBertTokenizer def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Any="[UNK]" , SCREAMING_SNAKE_CASE__ : Tuple="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : int="[CLS]" , SCREAMING_SNAKE_CASE__ : List[str]="[MASK]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get("strip_accents" , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): lowerCAmelCase__ = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop("type" ) ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = strip_accents lowerCAmelCase__ = tokenize_chinese_chars lowerCAmelCase__ = normalizer_class(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_lower_case def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ) -> Union[str, Any]: lowerCAmelCase__ = [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 : str , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: lowerCAmelCase__ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=sys.maxsize ) -> Union[str, Any]: lowerCAmelCase__ = "bilinear" lowerCAmelCase__ = max_size lowerCAmelCase__ = short_edge_length def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: lowerCAmelCase__ = [] for img in imgs: lowerCAmelCase__ , lowerCAmelCase__ = img.shape[:2] # later: provide list and randomly choose index for resize lowerCAmelCase__ = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img lowerCAmelCase__ = size * 1.0 / min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if h < w: lowerCAmelCase__ , lowerCAmelCase__ = size, scale * w else: lowerCAmelCase__ , lowerCAmelCase__ = scale * h, size if max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) > self.max_size: lowerCAmelCase__ = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = newh * scale lowerCAmelCase__ = neww * scale lowerCAmelCase__ = int(neww + 0.5 ) lowerCAmelCase__ = int(newh + 0.5 ) if img.dtype == np.uinta: lowerCAmelCase__ = Image.fromarray(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) lowerCAmelCase__ = np.asarray(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw lowerCAmelCase__ = nn.functional.interpolate( SCREAMING_SNAKE_CASE__ , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE__ ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE__ ) return img_augs class __lowerCamelCase : """simple docstring""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: lowerCAmelCase__ = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) lowerCAmelCase__ = cfg.INPUT.FORMAT lowerCAmelCase__ = cfg.SIZE_DIVISIBILITY lowerCAmelCase__ = cfg.PAD_VALUE lowerCAmelCase__ = cfg.INPUT.MAX_SIZE_TEST lowerCAmelCase__ = cfg.MODEL.DEVICE lowerCAmelCase__ = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase__ = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase__ = lambda SCREAMING_SNAKE_CASE__ : (x - self.pixel_mean) / self.pixel_std def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> Any: lowerCAmelCase__ = tuple(max(SCREAMING_SNAKE_CASE__ ) for s in zip(*[img.shape for img in images] ) ) lowerCAmelCase__ = [im.shape[-2:] for im in images] lowerCAmelCase__ = [ nn.functional.pad( SCREAMING_SNAKE_CASE__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ] return torch.stack(SCREAMING_SNAKE_CASE__ ), torch.tensor(SCREAMING_SNAKE_CASE__ ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=False ) -> Dict: with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [images] if single_image: assert len(SCREAMING_SNAKE_CASE__ ) == 1 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE__ , images.pop(SCREAMING_SNAKE_CASE__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE__ , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge lowerCAmelCase__ = torch.tensor([im.shape[:2] for im in images] ) lowerCAmelCase__ = self.aug(SCREAMING_SNAKE_CASE__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic lowerCAmelCase__ = [self.normalizer(SCREAMING_SNAKE_CASE__ ) for x in images] # now pad them to do the following operations lowerCAmelCase__ , lowerCAmelCase__ = self.pad(SCREAMING_SNAKE_CASE__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad lowerCAmelCase__ = torch.true_divide(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int ): """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple[int, int] ): """simple docstring""" assert torch.isfinite(lowerCAmelCase_ ).all(), "Box tensor contains infinite or NaN!" lowerCAmelCase__ , lowerCAmelCase__ = box_size tensor[:, 0].clamp_(min=0 , max=lowerCAmelCase_ ) tensor[:, 1].clamp_(min=0 , max=lowerCAmelCase_ ) tensor[:, 2].clamp_(min=0 , max=lowerCAmelCase_ ) tensor[:, 3].clamp_(min=0 , max=lowerCAmelCase_ )
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = (EulerDiscreteScheduler,) snake_case__ = 1_0 def a ( self : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: lowerCAmelCase__ = { "num_train_timesteps": 1_100, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**SCREAMING_SNAKE_CASE__ ) return config def a ( self : Optional[int] ) -> str: for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Optional[Any]: for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> int: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> Optional[int]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def a ( self : Any ) -> List[str]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(prediction_type="v_prediction" ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ , use_karras_sigmas=SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int = 0 ): """simple docstring""" lowerCAmelCase__ = length or len(lowerCAmelCase_ ) lowerCAmelCase__ = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: lowerCAmelCase__ , lowerCAmelCase__ = list_data[i + 1], list_data[i] lowerCAmelCase__ = True return list_data if not swapped else bubble_sort(lowerCAmelCase_ , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json', 'Salesforce/blip-vqa-capfit-large': ( 'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-base': ( 'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-large': ( 'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json' ), 'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json', 'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json', 'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json', 'Salesforce/blip-itm-large-flikr': ( 'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json' ), } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip_text_model" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_524 , SCREAMING_SNAKE_CASE__ : Optional[int]=768 , SCREAMING_SNAKE_CASE__ : Any=768 , SCREAMING_SNAKE_CASE__ : Any=3_072 , SCREAMING_SNAKE_CASE__ : Dict=768 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=512 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=1e-1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : str=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_522 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=102 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : int=True , **SCREAMING_SNAKE_CASE__ : int , ) -> Dict: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , sep_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = encoder_hidden_size lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = hidden_act lowerCAmelCase__ = initializer_range lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = is_decoder lowerCAmelCase__ = use_cache @classmethod def a ( cls : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : Any ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the text config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": lowerCAmelCase__ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip_vision_model" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Dict=768 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_072 , SCREAMING_SNAKE_CASE__ : Optional[int]=512 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : str=384 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=1e-5 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-1_0 , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = patch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = hidden_act @classmethod def a ( cls : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : str ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": lowerCAmelCase__ = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip" snake_case__ = True def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Any=512 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2.6_592 , SCREAMING_SNAKE_CASE__ : Tuple=256 , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) if text_config is None: lowerCAmelCase__ = {} logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values." ) if vision_config is None: lowerCAmelCase__ = {} logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values." ) lowerCAmelCase__ = BlipTextConfig(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = BlipVisionConfig(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.vision_config.hidden_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = logit_scale_init_value lowerCAmelCase__ = 1.0 lowerCAmelCase__ = 0.02 lowerCAmelCase__ = image_text_hidden_size @classmethod def a ( cls : Union[str, Any] , SCREAMING_SNAKE_CASE__ : BlipTextConfig , SCREAMING_SNAKE_CASE__ : BlipVisionConfig , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Optional[int]: lowerCAmelCase__ = copy.deepcopy(self.__dict__ ) lowerCAmelCase__ = self.text_config.to_dict() lowerCAmelCase__ = self.vision_config.to_dict() lowerCAmelCase__ = self.__class__.model_type return output
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , "decord" ) self.check_model_type(SCREAMING_SNAKE_CASE__ ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Any: lowerCAmelCase__ = {} if frame_sampling_rate is not None: lowerCAmelCase__ = frame_sampling_rate if num_frames is not None: lowerCAmelCase__ = num_frames lowerCAmelCase__ = {} if top_k is not None: lowerCAmelCase__ = top_k return preprocess_params, {}, postprocess_params def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, List[str]] , **SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1 ) -> Optional[Any]: if num_frames is None: lowerCAmelCase__ = self.model.config.num_frames if video.startswith("http://" ) or video.startswith("https://" ): lowerCAmelCase__ = BytesIO(requests.get(SCREAMING_SNAKE_CASE__ ).content ) lowerCAmelCase__ = VideoReader(SCREAMING_SNAKE_CASE__ ) videoreader.seek(0 ) lowerCAmelCase__ = 0 lowerCAmelCase__ = num_frames * frame_sampling_rate - 1 lowerCAmelCase__ = np.linspace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num=SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) lowerCAmelCase__ = videoreader.get_batch(SCREAMING_SNAKE_CASE__ ).asnumpy() lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) return model_inputs def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: lowerCAmelCase__ = self.model(**SCREAMING_SNAKE_CASE__ ) return model_outputs def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=5 ) -> Any: if top_k > self.model.config.num_labels: lowerCAmelCase__ = self.model.config.num_labels if self.framework == "pt": lowerCAmelCase__ = model_outputs.logits.softmax(-1 )[0] lowerCAmelCase__ , lowerCAmelCase__ = probs.topk(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) lowerCAmelCase__ = scores.tolist() lowerCAmelCase__ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )]
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key lowerCAmelCase__ = remove_duplicates(key.upper() ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # First fill cipher with key characters lowerCAmelCase__ = {alphabet[i]: char for i, char in enumerate(lowerCAmelCase_ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(lowerCAmelCase_ ) , 26 ): lowerCAmelCase__ = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 lowerCAmelCase__ = alphabet[i - offset] lowerCAmelCase__ = char return cipher_alphabet def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : dict[str, str] ): """simple docstring""" return "".join(cipher_map.get(lowerCAmelCase_ , lowerCAmelCase_ ) for ch in message.upper() ) def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : dict[str, str] ): """simple docstring""" lowerCAmelCase__ = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(lowerCAmelCase_ , lowerCAmelCase_ ) for ch in message.upper() ) def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter message to encode or decode: " ).strip() lowerCAmelCase__ = input("Enter keyword: " ).strip() lowerCAmelCase__ = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: lowerCAmelCase__ = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) lowerCAmelCase__ = create_cipher_map(lowerCAmelCase_ ) print(func(lowerCAmelCase_ , lowerCAmelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = StableDiffusionXLImgaImgPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def a ( self : Optional[Any] ) -> Dict: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE__ , addition_embed_type="text_time" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) lowerCAmelCase__ = EulerDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule="scaled_linear" , timestep_spacing="leading" , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=32 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_encoder_2": text_encoder_a, "tokenizer_2": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def a ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 ) -> List[str]: lowerCAmelCase__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = image / 2 + 0.5 if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "numpy", "strength": 0.75, } return inputs def a ( self : Any ) -> Tuple: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = StableDiffusionXLImgaImgPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase__ = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def a ( self : Any ) -> str: super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def a ( self : Optional[int] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Tuple ) -> Any: lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = StableDiffusionXLImgaImgPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) # forward without prompt embeds lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 3 * ["this is a negative prompt"] lowerCAmelCase__ = negative_prompt lowerCAmelCase__ = 3 * [inputs["prompt"]] lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 3 * ["this is a negative prompt"] lowerCAmelCase__ = 3 * [inputs.pop("prompt" )] ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) = sd_pipe.encode_prompt(SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe( **SCREAMING_SNAKE_CASE__ , prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , pooled_prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_pooled_prompt_embeds=SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @slow @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Dict ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def a ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any]="cpu" , SCREAMING_SNAKE_CASE__ : Tuple=torch.floataa , SCREAMING_SNAKE_CASE__ : List[str]=0 ) -> Optional[int]: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.random.RandomState(SCREAMING_SNAKE_CASE__ ).standard_normal((1, 4, 64, 64) ) lowerCAmelCase__ = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(device=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base" ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506] ) assert np.abs(image_slice - expected_slice ).max() < 7e-3
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "glpn" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Any=3 , SCREAMING_SNAKE_CASE__ : Tuple=4 , SCREAMING_SNAKE_CASE__ : List[str]=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : List[str]=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[32, 64, 160, 256] , SCREAMING_SNAKE_CASE__ : Any=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE__ : int=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE__ : str=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE__ : str="gelu" , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.02 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=1e-6 , SCREAMING_SNAKE_CASE__ : List[Any]=64 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=-1 , **SCREAMING_SNAKE_CASE__ : int , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = num_channels lowerCAmelCase__ = num_encoder_blocks lowerCAmelCase__ = depths lowerCAmelCase__ = sr_ratios lowerCAmelCase__ = hidden_sizes lowerCAmelCase__ = patch_sizes lowerCAmelCase__ = strides lowerCAmelCase__ = mlp_ratios lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = drop_path_rate lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = decoder_hidden_size lowerCAmelCase__ = max_depth lowerCAmelCase__ = head_in_index
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
from math import pi, sqrt, tan def _A ( lowerCAmelCase_ : float ): """simple docstring""" if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values" ) return 6 * side_length**2 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError("surface_area_cuboid() only accepts non-negative values" ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def _A ( lowerCAmelCase_ : float ): """simple docstring""" if radius < 0: raise ValueError("surface_area_sphere() only accepts non-negative values" ) return 4 * pi * radius**2 def _A ( lowerCAmelCase_ : float ): """simple docstring""" if radius < 0: raise ValueError("surface_area_hemisphere() only accepts non-negative values" ) return 3 * pi * radius**2 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if radius < 0 or height < 0: raise ValueError("surface_area_cone() only accepts non-negative values" ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( "surface_area_conical_frustum() only accepts non-negative values" ) lowerCAmelCase__ = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if radius < 0 or height < 0: raise ValueError("surface_area_cylinder() only accepts non-negative values" ) return 2 * pi * radius * (height + radius) def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError("surface_area_torus() only accepts non-negative values" ) if torus_radius < tube_radius: raise ValueError( "surface_area_torus() does not support spindle or self intersecting tori" ) return 4 * pow(lowerCAmelCase_ , 2 ) * torus_radius * tube_radius def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if length < 0 or width < 0: raise ValueError("area_rectangle() only accepts non-negative values" ) return length * width def _A ( lowerCAmelCase_ : float ): """simple docstring""" if side_length < 0: raise ValueError("area_square() only accepts non-negative values" ) return side_length**2 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values" ) return (base * height) / 2 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError("area_triangle_three_sides() only accepts non-negative values" ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError("Given three sides do not form a triangle" ) lowerCAmelCase__ = (sidea + sidea + sidea) / 2 lowerCAmelCase__ = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if base < 0 or height < 0: raise ValueError("area_parallelogram() only accepts non-negative values" ) return base * height def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values" ) return 1 / 2 * (basea + basea) * height def _A ( lowerCAmelCase_ : float ): """simple docstring""" if radius < 0: raise ValueError("area_circle() only accepts non-negative values" ) return pi * radius**2 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError("area_ellipse() only accepts non-negative values" ) return pi * radius_x * radius_y def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError("area_rhombus() only accepts non-negative values" ) return 1 / 2 * diagonal_a * diagonal_a def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : float ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or sides < 3: raise ValueError( "area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides" ) elif length < 0: raise ValueError( "area_reg_polygon() only accepts non-negative values as \ length of a side" ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('[DEMO] Areas of various geometric shapes: \n') print(F"""Rectangle: {area_rectangle(10, 20) = }""") print(F"""Square: {area_square(10) = }""") print(F"""Triangle: {area_triangle(10, 10) = }""") print(F"""Triangle: {area_triangle_three_sides(5, 12, 13) = }""") print(F"""Parallelogram: {area_parallelogram(10, 20) = }""") print(F"""Rhombus: {area_rhombus(10, 20) = }""") print(F"""Trapezium: {area_trapezium(10, 20, 30) = }""") print(F"""Circle: {area_circle(20) = }""") print(F"""Ellipse: {area_ellipse(10, 20) = }""") print('\nSurface Areas of various geometric shapes: \n') print(F"""Cube: {surface_area_cube(20) = }""") print(F"""Cuboid: {surface_area_cuboid(10, 20, 30) = }""") print(F"""Sphere: {surface_area_sphere(20) = }""") print(F"""Hemisphere: {surface_area_hemisphere(20) = }""") print(F"""Cone: {surface_area_cone(10, 20) = }""") print(F"""Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }""") print(F"""Cylinder: {surface_area_cylinder(10, 20) = }""") print(F"""Torus: {surface_area_torus(20, 10) = }""") print(F"""Equilateral Triangle: {area_reg_polygon(3, 10) = }""") print(F"""Square: {area_reg_polygon(4, 10) = }""") print(F"""Reqular Pentagon: {area_reg_polygon(5, 10) = }""")
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup UpperCamelCase = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def _A ( lowerCAmelCase_ : str = "mumbai" ): """simple docstring""" lowerCAmelCase__ = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): lowerCAmelCase__ = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() lowerCAmelCase__ = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(F"""Job {i:>2} is {job[0]} at {job[1]}""")
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
from __future__ import annotations import time import numpy as np UpperCamelCase = [8, 5, 9, 7] UpperCamelCase = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCamelCase = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : list[list[int]] , ) -> None: lowerCAmelCase__ = claim_vector lowerCAmelCase__ = allocated_resources_table lowerCAmelCase__ = maximum_claim_table def a ( self : List[Any] ) -> list[int]: return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def a ( self : Dict ) -> list[int]: return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def a ( self : List[Any] ) -> list[list[int]]: return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(SCREAMING_SNAKE_CASE__ ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def a ( self : Union[str, Any] ) -> dict[int, list[int]]: return {self.__need().index(SCREAMING_SNAKE_CASE__ ): i for i in self.__need()} def a ( self : Any , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> None: lowerCAmelCase__ = self.__need() lowerCAmelCase__ = self.__allocated_resources_table lowerCAmelCase__ = self.__available_resources() lowerCAmelCase__ = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n" ) while need_list: lowerCAmelCase__ = False for each_need in need_list: lowerCAmelCase__ = True for index, need in enumerate(SCREAMING_SNAKE_CASE__ ): if need > available_resources[index]: lowerCAmelCase__ = False break if execution: lowerCAmelCase__ = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: lowerCAmelCase__ = original_need_index print(f'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(SCREAMING_SNAKE_CASE__ ) # update available/freed resources stack lowerCAmelCase__ = np.array(SCREAMING_SNAKE_CASE__ ) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(SCREAMING_SNAKE_CASE__ ) for x in available_resources] ) ) break if safe: print("The process is in a safe state.\n" ) else: print("System in unsafe state. Aborting...\n" ) break def a ( self : List[str] ) -> str: print(" " * 9 + "Allocated Resource Table" ) for item in self.__allocated_resources_table: print( f'P{self.__allocated_resources_table.index(SCREAMING_SNAKE_CASE__ ) + 1}' + " ".join(f'{it:>8}' for it in item ) + "\n" ) print(" " * 9 + "System Resource Table" ) for item in self.__maximum_claim_table: print( f'P{self.__maximum_claim_table.index(SCREAMING_SNAKE_CASE__ ) + 1}' + " ".join(f'{it:>8}' for it in item ) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(SCREAMING_SNAKE_CASE__ ) for x in self.__claim_vector ) ) print( "Initial Available Resources: " + " ".join(str(SCREAMING_SNAKE_CASE__ ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
# 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
from decimal import Decimal, getcontext from math import ceil, factorial def _A ( lowerCAmelCase_ : int ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) lowerCAmelCase__ = precision lowerCAmelCase__ = ceil(precision / 14 ) lowerCAmelCase__ = 42_6880 * Decimal(1_0005 ).sqrt() lowerCAmelCase__ = 1 lowerCAmelCase__ = 1359_1409 lowerCAmelCase__ = Decimal(lowerCAmelCase_ ) for k in range(1 , lowerCAmelCase_ ): lowerCAmelCase__ = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3) linear_term += 5_4514_0134 exponential_term *= -26_2537_4126_4076_8000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCamelCase = 50 print(F"""The first {n} digits of pi is: {pi(n)}""")
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. UpperCamelCase = 10 def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" for i in range(lowerCAmelCase_ , lowerCAmelCase_ ): if array[i] == target: return i return -1 def _A ( lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = len(lowerCAmelCase_ ) while left <= right: if right - left < precision: return lin_search(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = (left + right) // 3 + 1 lowerCAmelCase__ = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: lowerCAmelCase__ = one_third - 1 elif array[two_third] < target: lowerCAmelCase__ = two_third + 1 else: lowerCAmelCase__ = one_third + 1 lowerCAmelCase__ = two_third - 1 else: return -1 def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" if left < right: if right - left < precision: return lin_search(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = (left + right) // 3 + 1 lowerCAmelCase__ = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowerCAmelCase_ , one_third - 1 , lowerCAmelCase_ , lowerCAmelCase_ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowerCAmelCase_ , lowerCAmelCase_ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = input('Enter numbers separated by comma:\n').strip() UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), F"List must be ordered.\n{collection}." UpperCamelCase = int(input('Enter the number to be found in the list:\n').strip()) UpperCamelCase = ite_ternary_search(collection, target) UpperCamelCase = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F"""Iterative search: {target} found at positions: {resulta}""") print(F"""Recursive search: {target} found at positions: {resulta}""") else: print('Not found')
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Optional[Any] ) -> Optional[int]: lowerCAmelCase__ = get_activation("swish" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def a ( self : List[str] ) -> List[str]: lowerCAmelCase__ = get_activation("silu" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def a ( self : List[str] ) -> Tuple: lowerCAmelCase__ = get_activation("mish" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def a ( self : List[str] ) -> Tuple: lowerCAmelCase__ = get_activation("gelu" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
import math import sys def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = "" try: with open(lowerCAmelCase_ , "rb" ) as binary_file: lowerCAmelCase__ = binary_file.read() for dat in data: lowerCAmelCase__ = F'{dat:08b}' result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = {"0": "0", "1": "1"} lowerCAmelCase__ , lowerCAmelCase__ = "", "" lowerCAmelCase__ = len(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowerCAmelCase__ = lexicon[curr_string] result += last_match_id lowerCAmelCase__ = last_match_id + "0" if math.loga(lowerCAmelCase_ ).is_integer(): lowerCAmelCase__ = {} for curr_key in list(lowerCAmelCase_ ): lowerCAmelCase__ = lexicon.pop(lowerCAmelCase_ ) lowerCAmelCase__ = new_lex lowerCAmelCase__ = last_match_id + "1" index += 1 lowerCAmelCase__ = "" return result def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = 8 try: with open(lowerCAmelCase_ , "wb" ) as opened_file: lowerCAmelCase__ = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowerCAmelCase_ , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = 0 for letter in data_bits: if letter == "1": break counter += 1 lowerCAmelCase__ = data_bits[counter:] lowerCAmelCase__ = data_bits[counter + 1 :] return data_bits def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = read_file_binary(lowerCAmelCase_ ) lowerCAmelCase__ = remove_prefix(lowerCAmelCase_ ) lowerCAmelCase__ = decompress_data(lowerCAmelCase_ ) write_file_binary(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _A ( lowerCAmelCase_ : int ): """simple docstring""" monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _A ( lowerCAmelCase_ : Any ): """simple docstring""" class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: lowerCAmelCase__ = metric_id class __lowerCamelCase : """simple docstring""" snake_case__ = [MetricMock(UpperCamelCase__ ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def a ( self : Dict ) -> Any: return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] ): """simple docstring""" if "tmp_path" in args: lowerCAmelCase__ = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase_ , match="https://huggingface.co/docs/evaluate" ): func(*lowerCAmelCase_ )
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "char" snake_case__ = "bpe" snake_case__ = "wp" UpperCamelCase = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "char_tokenizer"] snake_case__ = "ViTImageProcessor" snake_case__ = "MgpstrTokenizer" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : str ) -> str: lowerCAmelCase__ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) lowerCAmelCase__ = tokenizer lowerCAmelCase__ = AutoTokenizer.from_pretrained("gpt2" ) lowerCAmelCase__ = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None: lowerCAmelCase__ = self.char_tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is None: return inputs elif images is None: return encodings else: lowerCAmelCase__ = encodings["input_ids"] return inputs def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = sequences lowerCAmelCase__ = char_preds.size(0 ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "char" ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "bpe" ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "wp" ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] for i in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [char_scores[i], bpe_scores[i], wp_scores[i]] lowerCAmelCase__ = [char_strs[i], bpe_strs[i], wp_strs[i]] lowerCAmelCase__ = scores.index(max(SCREAMING_SNAKE_CASE__ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) lowerCAmelCase__ = {} lowerCAmelCase__ = final_strs lowerCAmelCase__ = final_scores lowerCAmelCase__ = char_strs lowerCAmelCase__ = bpe_strs lowerCAmelCase__ = wp_strs return out def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> str: if format == DecodeType.CHARACTER: lowerCAmelCase__ = self.char_decode lowerCAmelCase__ = 1 lowerCAmelCase__ = "[s]" elif format == DecodeType.BPE: lowerCAmelCase__ = self.bpe_decode lowerCAmelCase__ = 2 lowerCAmelCase__ = "#" elif format == DecodeType.WORDPIECE: lowerCAmelCase__ = self.wp_decode lowerCAmelCase__ = 102 lowerCAmelCase__ = "[SEP]" else: raise ValueError(f'Format {format} is not supported.' ) lowerCAmelCase__ , lowerCAmelCase__ = [], [] lowerCAmelCase__ = pred_logits.size(0 ) lowerCAmelCase__ = pred_logits.size(1 ) lowerCAmelCase__ , lowerCAmelCase__ = pred_logits.topk(1 , dim=-1 , largest=SCREAMING_SNAKE_CASE__ , sorted=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = preds_index.view(-1 , SCREAMING_SNAKE_CASE__ )[:, 1:] lowerCAmelCase__ = decoder(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = torch.nn.functional.softmax(SCREAMING_SNAKE_CASE__ , dim=2 ).max(dim=2 ) lowerCAmelCase__ = preds_max_prob[:, 1:] for index in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = preds_str[index].find(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = preds_str[index][:pred_eos] lowerCAmelCase__ = preds_index[index].cpu().tolist() lowerCAmelCase__ = pred_index.index(SCREAMING_SNAKE_CASE__ ) if eos_token in pred_index else -1 lowerCAmelCase__ = preds_max_prob[index][: pred_eos_index + 1] lowerCAmelCase__ = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(SCREAMING_SNAKE_CASE__ ) conf_scores.append(SCREAMING_SNAKE_CASE__ ) return dec_strs, conf_scores def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.char_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: return self.bpe_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.wp_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def _A ( lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Any=None ): """simple docstring""" return field(default_factory=lambda: default , metadata=lowerCAmelCase_ ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The csv file to plot."} , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Disable logarithmic scale when plotting"} , ) snake_case__ = field( default=UpperCamelCase__ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) snake_case__ = list_field( default=UpperCamelCase__ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" try: int(lowerCAmelCase_ ) return True except ValueError: return False def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" try: float(lowerCAmelCase_ ) return True except ValueError: return False class __lowerCamelCase : """simple docstring""" def __init__( self : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: lowerCAmelCase__ = args lowerCAmelCase__ = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline="" ) as csv_file: lowerCAmelCase__ = csv.DictReader(SCREAMING_SNAKE_CASE__ ) for row in reader: lowerCAmelCase__ = row["model"] self.result_dict[model_name]["bsz"].append(int(row["batch_size"] ) ) self.result_dict[model_name]["seq_len"].append(int(row["sequence_length"] ) ) if can_convert_to_int(row["result"] ): # value is not None lowerCAmelCase__ = int(row["result"] ) elif can_convert_to_float(row["result"] ): # value is not None lowerCAmelCase__ = float(row["result"] ) def a ( self : Tuple ) -> Optional[int]: lowerCAmelCase__ , lowerCAmelCase__ = plt.subplots() lowerCAmelCase__ = "Time usage" if self.args.is_time else "Memory usage" lowerCAmelCase__ = title_str + " for training" if self.args.is_train else title_str + " for inference" if not self.args.no_log_scale: # set logarithm scales ax.set_xscale("log" ) ax.set_yscale("log" ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): lowerCAmelCase__ = sorted(set(self.result_dict[model_name]["bsz"] ) ) lowerCAmelCase__ = sorted(set(self.result_dict[model_name]["seq_len"] ) ) lowerCAmelCase__ = self.result_dict[model_name]["result"] ((lowerCAmelCase__) , (lowerCAmelCase__)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) lowerCAmelCase__ = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: lowerCAmelCase__ = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=SCREAMING_SNAKE_CASE__ , ) else: lowerCAmelCase__ = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((lowerCAmelCase__) , (lowerCAmelCase__)) = ( ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz") ) lowerCAmelCase__ = np.asarray(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[: len(SCREAMING_SNAKE_CASE__ )] plt.scatter( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , label=f'{label_model_name} - {inner_loop_label}: {inner_loop_value}' ) plt.plot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "--" ) title_str += f' {label_model_name} vs.' lowerCAmelCase__ = title_str[:-4] lowerCAmelCase__ = "Time in s" if self.args.is_time else "Memory in MB" # plot plt.title(SCREAMING_SNAKE_CASE__ ) plt.xlabel(SCREAMING_SNAKE_CASE__ ) plt.ylabel(SCREAMING_SNAKE_CASE__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(lowerCAmelCase_ ) lowerCAmelCase__ = parser.parse_args_into_dataclasses()[0] lowerCAmelCase__ = Plot(args=lowerCAmelCase_ ) plot.plot() if __name__ == "__main__": main()
61
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
1
import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Any ) -> None: warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = (DEISMultistepScheduler,) snake_case__ = (("num_inference_steps", 2_5),) def a ( self : str , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: lowerCAmelCase__ = { "num_train_timesteps": 1_000, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "solver_order": 2, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = dict(self.forward_default_kwargs ) lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_sample lowerCAmelCase__ = 0.1 * sample lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCAmelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals lowerCAmelCase__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals lowerCAmelCase__ = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCAmelCase__ , lowerCAmelCase__ = sample, sample for t in range(SCREAMING_SNAKE_CASE__ , time_step + scheduler.config.solver_order + 1 ): lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample lowerCAmelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def a ( self : Any ) -> int: pass def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str=0 , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = dict(self.forward_default_kwargs ) lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_sample lowerCAmelCase__ = 0.1 * sample lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals (must be after setting timesteps) lowerCAmelCase__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residual (must be after setting timesteps) lowerCAmelCase__ = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample lowerCAmelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : str ) -> Tuple: if scheduler is None: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 10 lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def a ( self : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase__ = dict(self.forward_default_kwargs ) lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ ) for scheduler_class in self.scheduler_classes: lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_sample lowerCAmelCase__ = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE__ , "set_timesteps" ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE__ , "set_timesteps" ): lowerCAmelCase__ = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.10] lowerCAmelCase__ = dummy_past_residuals[: scheduler.config.solver_order] lowerCAmelCase__ = scheduler.timesteps[5] lowerCAmelCase__ = scheduler.timesteps[6] lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def a ( self : Any ) -> Optional[Any]: # make sure that iterating over schedulers with same config names gives same results # for defaults lowerCAmelCase__ = DEISMultistepScheduler(**self.get_scheduler_config() ) lowerCAmelCase__ = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 lowerCAmelCase__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) lowerCAmelCase__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ = UniPCMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ = DEISMultistepScheduler.from_config(scheduler.config ) lowerCAmelCase__ = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def a ( self : Union[str, Any] ) -> str: for timesteps in [25, 50, 100, 999, 1_000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[str]: self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , algorithm_type="deis" , solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , ) def a ( self : List[Any] ) -> Any: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Tuple: for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , algorithm_type=SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = self.full_loop( solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , algorithm_type=SCREAMING_SNAKE_CASE__ , ) assert not torch.isnan(SCREAMING_SNAKE_CASE__ ).any(), "Samples have nan numbers" def a ( self : int ) -> Tuple: self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__ ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[str]: for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE__ , time_step=0 ) def a ( self : Optional[int] ) -> int: lowerCAmelCase__ = self.full_loop() lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.full_loop(prediction_type="v_prediction" ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def a ( self : Optional[int] ) -> List[str]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE__ , dynamic_thresholding_ratio=0 ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = 10 lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample assert sample.dtype == torch.floataa
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py UpperCamelCase = '\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n author = "Lin, Chin-Yew and\n Och, Franz Josef",\n booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n month = "aug 23{--}aug 27",\n year = "2004",\n address = "Geneva, Switzerland",\n publisher = "COLING",\n url = "https://www.aclweb.org/anthology/C04-1072",\n pages = "501--507",\n}\n' UpperCamelCase = '\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n' UpperCamelCase = '\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample\n ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references)\n ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric("bleu")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results["bleu"])\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCamelCase ( datasets.Metric ): """simple docstring""" def a ( self : Optional[int] ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"] , reference_urls=[ "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=False ) -> int: lowerCAmelCase__ = compute_bleu( reference_corpus=SCREAMING_SNAKE_CASE__ , translation_corpus=SCREAMING_SNAKE_CASE__ , max_order=SCREAMING_SNAKE_CASE__ , smooth=SCREAMING_SNAKE_CASE__ ) ((lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__)) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = 1 for i in range(1 , num + 1 ): fact *= i return fact def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = 0 while number > 0: lowerCAmelCase__ = number % 10 sum_of_digits += last_digit lowerCAmelCase__ = number // 10 # Removing the last_digit from the given number return sum_of_digits def _A ( lowerCAmelCase_ : int = 100 ): """simple docstring""" lowerCAmelCase__ = factorial(lowerCAmelCase_ ) lowerCAmelCase__ = split_and_add(lowerCAmelCase_ ) return result if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
from __future__ import annotations def _A ( lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = list(range(len(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = [v / w for v, w in zip(lowerCAmelCase_ , lowerCAmelCase_ )] index.sort(key=lambda lowerCAmelCase_ : ratio[i] , reverse=lowerCAmelCase_ ) lowerCAmelCase__ = 0 lowerCAmelCase__ = [0] * len(lowerCAmelCase_ ) for i in index: if weight[i] <= capacity: lowerCAmelCase__ = 1 max_value += value[i] capacity -= weight[i] else: lowerCAmelCase__ = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
1
from __future__ import annotations from collections.abc import Callable def _A ( lowerCAmelCase_ : Callable[[int | float], int | float] , lowerCAmelCase_ : int | float , lowerCAmelCase_ : int | float , lowerCAmelCase_ : int = 100 , ): """simple docstring""" lowerCAmelCase__ = x_start lowerCAmelCase__ = fnc(lowerCAmelCase_ ) lowerCAmelCase__ = 0.0 for _ in range(lowerCAmelCase_ ): # Approximates small segments of curve as linear and solve # for trapezoidal area lowerCAmelCase__ = (x_end - x_start) / steps + xa lowerCAmelCase__ = fnc(lowerCAmelCase_ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step lowerCAmelCase__ = xa lowerCAmelCase__ = fxa return area if __name__ == "__main__": def _A ( lowerCAmelCase_ : int ): """simple docstring""" return x**3 + x**2 print('f(x) = x^3 + x^2') print('The area between the curve, x = -5, x = 5 and the x axis is:') UpperCamelCase = 10 while i <= 10_0000: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
from __future__ import annotations from random import random class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : int | None = None ) -> Optional[int]: lowerCAmelCase__ = value lowerCAmelCase__ = random() lowerCAmelCase__ = None lowerCAmelCase__ = None def __repr__( self : List[Any] ) -> str: from pprint import pformat if self.left is None and self.right is None: return f'\'{self.value}: {self.prior:.5}\'' else: return pformat( {f'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self : Dict ) -> str: lowerCAmelCase__ = str(self.value ) + " " lowerCAmelCase__ = str(self.left or "" ) lowerCAmelCase__ = str(self.right or "" ) return value + left + right def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ): """simple docstring""" if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: lowerCAmelCase__ , lowerCAmelCase__ = split(root.left , lowerCAmelCase_ ) return left, root else: lowerCAmelCase__ , lowerCAmelCase__ = split(root.right , lowerCAmelCase_ ) return root, right def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : Node | None ): """simple docstring""" if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: lowerCAmelCase__ = merge(left.right , lowerCAmelCase_ ) return left else: lowerCAmelCase__ = merge(lowerCAmelCase_ , right.left ) return right def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = Node(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = split(lowerCAmelCase_ , lowerCAmelCase_ ) return merge(merge(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ = split(lowerCAmelCase_ , value - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = split(lowerCAmelCase_ , lowerCAmelCase_ ) return merge(lowerCAmelCase_ , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" if not root: # None return else: inorder(root.left ) print(root.value , end="," ) inorder(root.right ) def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : str ): """simple docstring""" for arg in args.split(): if arg[0] == "+": lowerCAmelCase__ = insert(lowerCAmelCase_ , int(arg[1:] ) ) elif arg[0] == "-": lowerCAmelCase__ = erase(lowerCAmelCase_ , int(arg[1:] ) ) else: print("Unknown command" ) return root def _A ( ): """simple docstring""" lowerCAmelCase__ = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) lowerCAmelCase__ = input() while args != "q": lowerCAmelCase__ = interact_treap(lowerCAmelCase_ , lowerCAmelCase_ ) print(lowerCAmelCase_ ) lowerCAmelCase__ = input() print("good by!" ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCamelCase = pytest.mark.integration UpperCamelCase = {'comet'} UpperCamelCase = importlib.util.find_spec('fairseq') is not None UpperCamelCase = {'code_eval'} UpperCamelCase = os.name == 'nt' UpperCamelCase = {'bertscore', 'frugalscore', 'perplexity'} UpperCamelCase = importlib.util.find_spec('transformers') is not None def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self : List[Any] , lowerCAmelCase_ : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , lowerCAmelCase_ ) return wrapper def _A ( lowerCAmelCase_ : str ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self : str , lowerCAmelCase_ : Tuple ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , lowerCAmelCase_ ) return wrapper def _A ( lowerCAmelCase_ : str ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self : Any , lowerCAmelCase_ : Dict ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , lowerCAmelCase_ ) return wrapper def _A ( ): """simple docstring""" lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) @local class __lowerCamelCase ( parameterized.TestCase ): """simple docstring""" snake_case__ = {} snake_case__ = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def a ( self : int , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , SCREAMING_SNAKE_CASE__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=SCREAMING_SNAKE_CASE__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(SCREAMING_SNAKE_CASE__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , raise_on_error=SCREAMING_SNAKE_CASE__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , SCREAMING_SNAKE_CASE__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , raise_on_error=SCREAMING_SNAKE_CASE__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](SCREAMING_SNAKE_CASE__ ): yield else: yield @contextmanager def a ( self : List[str] ) -> Optional[int]: def load_local_metric(SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return load_metric(os.path.join("metrics" , SCREAMING_SNAKE_CASE__ ) , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def a ( cls : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: def wrapper(SCREAMING_SNAKE_CASE__ : int ): lowerCAmelCase__ = contextmanager(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" import torch def bert_cos_score_idf(lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str , *lowerCAmelCase_ : Tuple , **lowerCAmelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowerCAmelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" def load_from_checkpoint(lowerCAmelCase_ : Dict ): class __lowerCamelCase : """simple docstring""" def a ( self : Any , SCREAMING_SNAKE_CASE__ : Any , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : str ) -> int: assert len(SCREAMING_SNAKE_CASE__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def _A ( ): """simple docstring""" lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}' with pytest.raises(lowerCAmelCase_ , match=re.escape(lowerCAmelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=lowerCAmelCase_ )
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
from functools import lru_cache @lru_cache def _A ( lowerCAmelCase_ : int ): """simple docstring""" if num < 0: raise ValueError("Number should not be negative." ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCamelCase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return max(metric_fn(lowerCAmelCase_ , lowerCAmelCase_ ) for gt in ground_truths ) def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = [line.strip() for line in open(lowerCAmelCase_ , "r" ).readlines()] lowerCAmelCase__ = [] if args.gold_data_mode == "qa": lowerCAmelCase__ = pd.read_csv(lowerCAmelCase_ , sep="\t" , header=lowerCAmelCase_ ) for answer_list in data[1]: lowerCAmelCase__ = ast.literal_eval(lowerCAmelCase_ ) answers.append(lowerCAmelCase_ ) else: lowerCAmelCase__ = [line.strip() for line in open(lowerCAmelCase_ , "r" ).readlines()] lowerCAmelCase__ = [[reference] for reference in references] lowerCAmelCase__ = lowerCAmelCase__ = lowerCAmelCase__ = 0 for prediction, ground_truths in zip(lowerCAmelCase_ , lowerCAmelCase_ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) fa += metric_max_over_ground_truths(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = 100.0 * em / total lowerCAmelCase__ = 100.0 * fa / total logger.info(F'F1: {fa:.2f}' ) logger.info(F'EM: {em:.2f}' ) def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict ): """simple docstring""" lowerCAmelCase__ = args.k lowerCAmelCase__ = [line.strip() for line in open(lowerCAmelCase_ , "r" ).readlines()] lowerCAmelCase__ = [line.strip() for line in open(lowerCAmelCase_ , "r" ).readlines()] lowerCAmelCase__ = lowerCAmelCase__ = 0 for hypo, reference in zip(lowerCAmelCase_ , lowerCAmelCase_ ): lowerCAmelCase__ = set(hypo.split("\t" )[:k] ) lowerCAmelCase__ = set(reference.split("\t" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k lowerCAmelCase__ = 100.0 * em / total logger.info(F'Precision@{k}: {em: .2f}' ) def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : Any , lowerCAmelCase_ : Any ): """simple docstring""" def strip_title(lowerCAmelCase_ : int ): if title.startswith("\"" ): lowerCAmelCase__ = title[1:] if title.endswith("\"" ): lowerCAmelCase__ = title[:-1] return title lowerCAmelCase__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase_ , return_tensors="pt" , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , )["input_ids"].to(args.device ) lowerCAmelCase__ = rag_model.rag.question_encoder(lowerCAmelCase_ ) lowerCAmelCase__ = question_enc_outputs[0] lowerCAmelCase__ = rag_model.retriever( lowerCAmelCase_ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="pt" , ) lowerCAmelCase__ = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) lowerCAmelCase__ = [] for docs in all_docs: lowerCAmelCase__ = [strip_title(lowerCAmelCase_ ) for title in docs["title"]] provenance_strings.append("\t".join(lowerCAmelCase_ ) ) return provenance_strings def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : str ): """simple docstring""" with torch.no_grad(): lowerCAmelCase__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase_ , return_tensors="pt" , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ ) lowerCAmelCase__ = inputs_dict.input_ids.to(args.device ) lowerCAmelCase__ = inputs_dict.attention_mask.to(args.device ) lowerCAmelCase__ = rag_model.generate( # rag_model overwrites generate lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase_ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) lowerCAmelCase__ = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) if args.print_predictions: for q, a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): logger.info("Q: {} - A: {}".format(lowerCAmelCase_ , lowerCAmelCase_ ) ) return answers def _A ( ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--model_type" , choices=["rag_sequence", "rag_token", "bart"] , type=lowerCAmelCase_ , help=( "RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the" " model_name_or_path" ) , ) parser.add_argument( "--index_name" , default=lowerCAmelCase_ , choices=["exact", "compressed", "legacy"] , type=lowerCAmelCase_ , help="RAG model retriever type" , ) parser.add_argument( "--index_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Path to the retrieval index" , ) parser.add_argument("--n_docs" , default=5 , type=lowerCAmelCase_ , help="Number of retrieved docs" ) parser.add_argument( "--model_name_or_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to pretrained checkpoints or model identifier from huggingface.co/models" , ) parser.add_argument( "--eval_mode" , choices=["e2e", "retrieval"] , default="e2e" , type=lowerCAmelCase_ , help=( "Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates" " precision@k." ) , ) parser.add_argument("--k" , default=1 , type=lowerCAmelCase_ , help="k for the precision@k calculation" ) parser.add_argument( "--evaluation_set" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to a file containing evaluation samples" , ) parser.add_argument( "--gold_data_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to a tab-separated file with gold samples" , ) parser.add_argument( "--gold_data_mode" , default="qa" , type=lowerCAmelCase_ , choices=["qa", "ans"] , help=( "Format of the gold data file" "qa - a single line in the following format: question [tab] answer_list" "ans - a single line of the gold file contains the expected answer string" ) , ) parser.add_argument( "--predictions_path" , type=lowerCAmelCase_ , default="predictions.txt" , help="Name of the predictions file, to be stored in the checkpoints directory" , ) parser.add_argument( "--eval_all_checkpoints" , action="store_true" , help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number" , ) parser.add_argument( "--eval_batch_size" , default=8 , type=lowerCAmelCase_ , help="Batch size per GPU/CPU for evaluation." , ) parser.add_argument( "--recalculate" , help="Recalculate predictions even if the prediction file exists" , action="store_true" , ) parser.add_argument( "--num_beams" , default=4 , type=lowerCAmelCase_ , help="Number of beams to be used when generating answers" , ) parser.add_argument("--min_length" , default=1 , type=lowerCAmelCase_ , help="Min length of the generated answers" ) parser.add_argument("--max_length" , default=50 , type=lowerCAmelCase_ , help="Max length of the generated answers" ) parser.add_argument( "--print_predictions" , action="store_true" , help="If True, prints predictions while evaluating." , ) parser.add_argument( "--print_docs" , action="store_true" , help="If True, prints docs retried while generating." , ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) return args def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = {} if args.model_type is None: lowerCAmelCase__ = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("rag" ): lowerCAmelCase__ = RagTokenForGeneration if args.model_type == "rag_token" else RagSequenceForGeneration lowerCAmelCase__ = args.n_docs if args.index_name is not None: lowerCAmelCase__ = args.index_name if args.index_path is not None: lowerCAmelCase__ = args.index_path else: lowerCAmelCase__ = BartForConditionalGeneration lowerCAmelCase__ = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("Evaluate the following checkpoints: %s" , lowerCAmelCase_ ) lowerCAmelCase__ = get_scores if args.eval_mode == "e2e" else get_precision_at_k lowerCAmelCase__ = evaluate_batch_eae if args.eval_mode == "e2e" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("Calculating metrics based on an existing predictions file: {}".format(args.predictions_path ) ) score_fn(lowerCAmelCase_ , args.predictions_path , args.gold_data_path ) continue logger.info("***** Running evaluation for {} *****".format(lowerCAmelCase_ ) ) logger.info(" Batch size = %d" , args.eval_batch_size ) logger.info(" Predictions will be stored under {}".format(args.predictions_path ) ) if args.model_type.startswith("rag" ): lowerCAmelCase__ = RagRetriever.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) lowerCAmelCase__ = model_class.from_pretrained(lowerCAmelCase_ , retriever=lowerCAmelCase_ , **lowerCAmelCase_ ) model.retriever.init_retrieval() else: lowerCAmelCase__ = model_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) model.to(args.device ) with open(args.evaluation_set , "r" ) as eval_file, open(args.predictions_path , "w" ) as preds_file: lowerCAmelCase__ = [] for line in tqdm(lowerCAmelCase_ ): questions.append(line.strip() ) if len(lowerCAmelCase_ ) == args.eval_batch_size: lowerCAmelCase__ = evaluate_batch_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) preds_file.write("\n".join(lowerCAmelCase_ ) + "\n" ) preds_file.flush() lowerCAmelCase__ = [] if len(lowerCAmelCase_ ) > 0: lowerCAmelCase__ = evaluate_batch_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) preds_file.write("\n".join(lowerCAmelCase_ ) ) preds_file.flush() score_fn(lowerCAmelCase_ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCamelCase = get_args() main(args)
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
def _A ( lowerCAmelCase_ : list[int] , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = int(lowerCAmelCase_ ) # Initialize Result lowerCAmelCase__ = [] # Traverse through all denomination for denomination in reversed(lowerCAmelCase_ ): # Find denominations while int(lowerCAmelCase_ ) >= int(lowerCAmelCase_ ): total_value -= int(lowerCAmelCase_ ) answer.append(lowerCAmelCase_ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCamelCase = [] UpperCamelCase = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCamelCase = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) UpperCamelCase = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCamelCase = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCamelCase = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F"""Following is minimal change for {value}: """) UpperCamelCase = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
def _A ( lowerCAmelCase_ : int = 10 , lowerCAmelCase_ : int = 1000 , lowerCAmelCase_ : bool = True ): """simple docstring""" assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)" ) return min_val if option else max_val def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" return int((number_a + number_a) / 2 ) def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)" ) if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value" ) def answer(lowerCAmelCase_ : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started..." ) lowerCAmelCase__ = lower lowerCAmelCase__ = higher lowerCAmelCase__ = [] while True: lowerCAmelCase__ = get_avg(lowerCAmelCase_ , lowerCAmelCase_ ) last_numbers.append(lowerCAmelCase_ ) if answer(lowerCAmelCase_ ) == "low": lowerCAmelCase__ = number elif answer(lowerCAmelCase_ ) == "high": lowerCAmelCase__ = number else: break print(F'guess the number : {last_numbers[-1]}' ) print(F'details : {last_numbers!s}' ) def _A ( ): """simple docstring""" lowerCAmelCase__ = int(input("Enter lower value : " ).strip() ) lowerCAmelCase__ = int(input("Enter high value : " ).strip() ) lowerCAmelCase__ = int(input("Enter value to guess : " ).strip() ) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = CpmAntTokenizer snake_case__ = False def a ( self : Any ) -> str: super().setUp() lowerCAmelCase__ = [ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) @tooslow def a ( self : Optional[int] ) -> int: lowerCAmelCase__ = CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b" ) lowerCAmelCase__ = "今天天气真好!" lowerCAmelCase__ = ["今天", "天气", "真", "好", "!"] lowerCAmelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "今天天气真好!" lowerCAmelCase__ = [tokenizer.bos_token] + tokens lowerCAmelCase__ = [6, 9_802, 14_962, 2_082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
61
# 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
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 __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = (DPMSolverSDEScheduler,) snake_case__ = 1_0 def a ( self : Dict , **SCREAMING_SNAKE_CASE__ : str ) -> str: lowerCAmelCase__ = { "num_train_timesteps": 1_100, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def a ( self : Any ) -> int: for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Union[str, Any]: for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> int: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Dict: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Optional[Any]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_821_044_921_875 ) < 1e-2 assert abs(result_mean.item() - 0.2_178_705_964_565_277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_352_111_816_406 ) < 1e-2 assert abs(result_mean.item() - 0.22_342_906_892_299_652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562 ) < 1e-2 assert abs(result_mean.item() - 0.211_619_570_851_326 ) < 1e-3 def a ( self : Optional[Any] ) -> Optional[int]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(prediction_type="v_prediction" ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_149_200_439_453 ) < 1e-2 assert abs(result_mean.item() - 0.16_226_289_014_816_284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_663_360_595_703 ) < 1e-2 assert abs(result_mean.item() - 0.16_688_326_001_167_297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_487_548_828_125 ) < 1e-2 assert abs(result_mean.item() - 0.1_560_530_662_536_621 ) < 1e-3 def a ( self : Tuple ) -> Optional[int]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_957_397_460_938 ) < 1e-2 assert abs(result_mean.item() - 0.21_805_934_607_982_635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_353_637_695_312 ) < 1e-2 assert abs(result_mean.item() - 0.22_342_908_382_415_771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562 ) < 1e-2 assert abs(result_mean.item() - 0.211_619_570_851_326 ) < 1e-3 def a ( self : List[str] ) -> List[str]: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ , use_karras_sigmas=SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_974_135_742_188 ) < 1e-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_653_564_453_125 ) < 1e-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_135_223_388_672 ) < 1e-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1e-2
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'microsoft/focalnet-tiny': 'https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json', } class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" snake_case__ = "focalnet" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str=224 , SCREAMING_SNAKE_CASE__ : str=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[Any]=96 , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Tuple=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE__ : Dict=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__ : Optional[int]=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : Optional[int]=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : List[Any]=4.0 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1e-4 , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Any=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> str: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = embed_dim lowerCAmelCase__ = use_conv_embed lowerCAmelCase__ = hidden_sizes lowerCAmelCase__ = depths lowerCAmelCase__ = focal_levels lowerCAmelCase__ = focal_windows lowerCAmelCase__ = hidden_act lowerCAmelCase__ = mlp_ratio lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = drop_path_rate lowerCAmelCase__ = use_layerscale lowerCAmelCase__ = layerscale_value lowerCAmelCase__ = use_post_layernorm lowerCAmelCase__ = use_post_layernorm_in_modulation lowerCAmelCase__ = normalize_modulator lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = encoder_stride lowerCAmelCase__ = ["stem"] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] lowerCAmelCase__ , lowerCAmelCase__ = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ , out_indices=SCREAMING_SNAKE_CASE__ , stage_names=self.stage_names )
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" lowerCAmelCase__ = filter(lambda lowerCAmelCase_ : p.requires_grad , model.parameters() ) lowerCAmelCase__ = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase = logging.getLogger(__name__) def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any ): """simple docstring""" if metric == "rouge2": lowerCAmelCase__ = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": lowerCAmelCase__ = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": lowerCAmelCase__ = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": lowerCAmelCase__ = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) lowerCAmelCase__ = ModelCheckpoint( dirpath=lowerCAmelCase_ , filename=lowerCAmelCase_ , monitor=F'val_{metric}' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict ): """simple docstring""" return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowerCAmelCase_ , verbose=lowerCAmelCase_ , ) class __lowerCamelCase ( pl.Callback ): """simple docstring""" def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Dict: lowerCAmelCase__ = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(SCREAMING_SNAKE_CASE__ ) @rank_zero_only def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : pl.Trainer , SCREAMING_SNAKE_CASE__ : pl.LightningModule , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> None: logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) lowerCAmelCase__ = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results lowerCAmelCase__ = Path(pl_module.hparams.output_dir ) if type_path == "test": lowerCAmelCase__ = od / "test_results.txt" lowerCAmelCase__ = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. lowerCAmelCase__ = od / f'{type_path}_results/{trainer.global_step:05d}.txt' lowerCAmelCase__ = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) generations_file.parent.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , "a+" ) as writer: for key in sorted(SCREAMING_SNAKE_CASE__ ): if key in ["log", "progress_bar", "preds"]: continue lowerCAmelCase__ = metrics[key] if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): lowerCAmelCase__ = val.item() lowerCAmelCase__ = f'{key}: {val:.6f}\n' writer.write(SCREAMING_SNAKE_CASE__ ) if not save_generations: return if "preds" in metrics: lowerCAmelCase__ = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(SCREAMING_SNAKE_CASE__ ) @rank_zero_only def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: try: lowerCAmelCase__ = pl_module.model.model.num_parameters() except AttributeError: lowerCAmelCase__ = pl_module.model.num_parameters() lowerCAmelCase__ = count_trainable_parameters(SCREAMING_SNAKE_CASE__ ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : pl.Trainer , SCREAMING_SNAKE_CASE__ : pl.LightningModule ) -> List[str]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "test" ) @rank_zero_only def a ( self : Dict , SCREAMING_SNAKE_CASE__ : pl.Trainer , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = 0 for ch in input_str: lowerCAmelCase__ = ord(lowerCAmelCase_ ) lowerCAmelCase__ = pow(2 , lowerCAmelCase_ ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline UpperCamelCase = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCamelCase ( datasets.BuilderConfig ): """simple docstring""" snake_case__ = None snake_case__ = "utf-8" snake_case__ = None snake_case__ = None snake_case__ = True # deprecated snake_case__ = None # deprecated snake_case__ = 1_0 << 2_0 # 10MB snake_case__ = None class __lowerCamelCase ( datasets.ArrowBasedBuilder ): """simple docstring""" snake_case__ = JsonConfig def a ( self : Optional[int] ) -> Optional[Any]: if self.config.block_size is not None: logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead" ) lowerCAmelCase__ = self.config.block_size if self.config.use_threads is not True: logger.warning( "The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore." ) if self.config.newlines_in_values is not None: raise ValueError("The JSON loader parameter `newlines_in_values` is no longer supported" ) return datasets.DatasetInfo(features=self.config.features ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: 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__ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE__ , (str, list, tuple) ): lowerCAmelCase__ = data_files if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [files] lowerCAmelCase__ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] lowerCAmelCase__ = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [files] lowerCAmelCase__ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE__ ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE__ , gen_kwargs={"files": files} ) ) return splits def a ( self : str , SCREAMING_SNAKE_CASE__ : pa.Table ) -> pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): lowerCAmelCase__ = self.config.features.arrow_schema.field(SCREAMING_SNAKE_CASE__ ).type lowerCAmelCase__ = pa_table.append_column(SCREAMING_SNAKE_CASE__ , pa.array([None] * len(SCREAMING_SNAKE_CASE__ ) , type=SCREAMING_SNAKE_CASE__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example lowerCAmelCase__ = table_cast(SCREAMING_SNAKE_CASE__ , self.config.features.arrow_schema ) return pa_table def a ( self : str , SCREAMING_SNAKE_CASE__ : Dict ) -> str: for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(SCREAMING_SNAKE_CASE__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: lowerCAmelCase__ = json.load(SCREAMING_SNAKE_CASE__ ) # We keep only the field we are interested in lowerCAmelCase__ = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): lowerCAmelCase__ = set().union(*[row.keys() for row in dataset] ) lowerCAmelCase__ = {col: [row.get(SCREAMING_SNAKE_CASE__ ) for row in dataset] for col in keys} else: lowerCAmelCase__ = dataset lowerCAmelCase__ = pa.Table.from_pydict(SCREAMING_SNAKE_CASE__ ) yield file_idx, self._cast_table(SCREAMING_SNAKE_CASE__ ) # If the file has one json object per line else: with open(SCREAMING_SNAKE_CASE__ , "rb" ) as f: lowerCAmelCase__ = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small lowerCAmelCase__ = max(self.config.chunksize // 32 , 16 << 10 ) lowerCAmelCase__ = ( self.config.encoding_errors if self.config.encoding_errors is not None else "strict" ) while True: lowerCAmelCase__ = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(SCREAMING_SNAKE_CASE__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": lowerCAmelCase__ = batch.decode(self.config.encoding , errors=SCREAMING_SNAKE_CASE__ ).encode("utf-8" ) try: while True: try: lowerCAmelCase__ = paj.read_json( io.BytesIO(SCREAMING_SNAKE_CASE__ ) , read_options=paj.ReadOptions(block_size=SCREAMING_SNAKE_CASE__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(SCREAMING_SNAKE_CASE__ , pa.ArrowInvalid ) and "straddling" not in str(SCREAMING_SNAKE_CASE__ ) or block_size > len(SCREAMING_SNAKE_CASE__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f'Batch of {len(SCREAMING_SNAKE_CASE__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( SCREAMING_SNAKE_CASE__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: lowerCAmelCase__ = json.load(SCREAMING_SNAKE_CASE__ ) except json.JSONDecodeError: logger.error(f'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # list is the only sequence type supported in JSON try: lowerCAmelCase__ = set().union(*[row.keys() for row in dataset] ) lowerCAmelCase__ = {col: [row.get(SCREAMING_SNAKE_CASE__ ) for row in dataset] for col in keys} lowerCAmelCase__ = pa.Table.from_pydict(SCREAMING_SNAKE_CASE__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE__ )}: {e}' ) raise ValueError(f'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(SCREAMING_SNAKE_CASE__ ) break else: logger.error(f'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE__ )}: {e}' ) raise ValueError( f'Not able to read records in the JSON file at {file}. ' f'You should probably indicate the field of the JSON file containing your records. ' f'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' f'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE__ ) batch_idx += 1
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = 42 snake_case__ = None snake_case__ = None UpperCamelCase = namedtuple('CoinsDistribResult', 'moves excess') def _A ( lowerCAmelCase_ : TreeNode | None ): """simple docstring""" if root is None: return 0 # Validation def count_nodes(lowerCAmelCase_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(lowerCAmelCase_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(lowerCAmelCase_ ) != count_coins(lowerCAmelCase_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(lowerCAmelCase_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowerCAmelCase__ , lowerCAmelCase__ = get_distrib(node.left ) lowerCAmelCase__ , lowerCAmelCase__ = get_distrib(node.right ) lowerCAmelCase__ = 1 - left_distrib_excess lowerCAmelCase__ = 1 - right_distrib_excess lowerCAmelCase__ = ( left_distrib_moves + right_distrib_moves + abs(lowerCAmelCase_ ) + abs(lowerCAmelCase_ ) ) lowerCAmelCase__ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(lowerCAmelCase_ , lowerCAmelCase_ ) return get_distrib(lowerCAmelCase_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
UpperCamelCase = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} UpperCamelCase = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _A ( lowerCAmelCase_ : dict[int, list[int]] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[bool] ): """simple docstring""" lowerCAmelCase__ = True lowerCAmelCase__ = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) order.append(lowerCAmelCase_ ) return order def _A ( lowerCAmelCase_ : dict[int, list[int]] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[bool] ): """simple docstring""" lowerCAmelCase__ = True lowerCAmelCase__ = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return component def _A ( lowerCAmelCase_ : dict[int, list[int]] ): """simple docstring""" lowerCAmelCase__ = len(lowerCAmelCase_ ) * [False] lowerCAmelCase__ = {vert: [] for vert in range(len(lowerCAmelCase_ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(lowerCAmelCase_ ) lowerCAmelCase__ = [] for i, was_visited in enumerate(lowerCAmelCase_ ): if not was_visited: order += topology_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = len(lowerCAmelCase_ ) * [False] for i in range(len(lowerCAmelCase_ ) ): lowerCAmelCase__ = order[len(lowerCAmelCase_ ) - i - 1] if not visited[vert]: lowerCAmelCase__ = find_components(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) components_list.append(lowerCAmelCase_ ) return components_list
61
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
1
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def _A ( lowerCAmelCase_ : Optional[int]=32 , lowerCAmelCase_ : Dict=10 , lowerCAmelCase_ : Union[str, Any]=100 , lowerCAmelCase_ : List[Any]=1026 , lowerCAmelCase_ : Any=True , lowerCAmelCase_ : Any="data/tokenized_stories_train_wikitext103.jbl" , lowerCAmelCase_ : Optional[Any]="igf_context_pairs.jbl" , ): """simple docstring""" set_seed(3 ) # generate train_data and objective_set lowerCAmelCase__ , lowerCAmelCase__ = generate_datasets( lowerCAmelCase_ , lowerCAmelCase_ , number=lowerCAmelCase_ , min_len=1026 , trim=lowerCAmelCase_ ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? lowerCAmelCase__ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # load pretrained model lowerCAmelCase__ = load_gpta("gpt2" ).to(lowerCAmelCase_ ) print("computing perplexity on objective set" ) lowerCAmelCase__ = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).item() print("perplexity on objective set:" , lowerCAmelCase_ ) # collect igf pairs and save to file demo.jbl collect_objective_set(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : List[str]=15 , lowerCAmelCase_ : int=128 , lowerCAmelCase_ : Optional[int]=100 , lowerCAmelCase_ : Dict="igf_model.pt" , ): """simple docstring""" set_seed(42 ) # Load pre-trained model lowerCAmelCase__ = GPTaLMHeadModel.from_pretrained("gpt2" ) # Initialize secondary learner to use embedding weights of model lowerCAmelCase__ = SecondaryLearner(lowerCAmelCase_ ) # Train secondary learner lowerCAmelCase__ = train_secondary_learner( lowerCAmelCase_ , lowerCAmelCase_ , max_epochs=lowerCAmelCase_ , batch_size=lowerCAmelCase_ , eval_freq=100 , igf_model_path=lowerCAmelCase_ , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any=32 , lowerCAmelCase_ : List[str]=1000 , lowerCAmelCase_ : Optional[Any]=16 , lowerCAmelCase_ : str=1.0 , lowerCAmelCase_ : Dict=recopy_gpta , lowerCAmelCase_ : int=None , lowerCAmelCase_ : List[Any]=10 , lowerCAmelCase_ : List[Any]="gpt2_finetuned.pt" , ): """simple docstring""" lowerCAmelCase__ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) lowerCAmelCase__ = RandomSampler(lowerCAmelCase_ ) lowerCAmelCase__ = DataLoader(lowerCAmelCase_ , sampler=lowerCAmelCase_ ) lowerCAmelCase__ = max_steps // (len(lowerCAmelCase_ )) + 1 lowerCAmelCase__ = 0 lowerCAmelCase__ = torch.zeros((1, context_len) , dtype=torch.long , device=lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = recopy_model(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) model.train() if secondary_learner is not None: secondary_learner.to(lowerCAmelCase_ ) secondary_learner.eval() lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = [] lowerCAmelCase__ = [] # Compute the performance of the transformer model at the beginning lowerCAmelCase__ = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) test_perps.append(lowerCAmelCase_ ) print("Test perplexity, step" , lowerCAmelCase_ , ":" , lowerCAmelCase_ ) for epoch in range(int(lowerCAmelCase_ ) ): for step, example in enumerate(lowerCAmelCase_ ): torch.cuda.empty_cache() lowerCAmelCase__ = random.randint(0 , example.size(2 ) - context_len - 1 ) lowerCAmelCase__ = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() lowerCAmelCase__ = model(lowerCAmelCase_ , labels=lowerCAmelCase_ ) lowerCAmelCase__ = True if secondary_learner is not None: lowerCAmelCase__ = secondary_learner.forward( torch.tensor(lowerCAmelCase_ , dtype=torch.long , device=lowerCAmelCase_ ).unsqueeze(0 ) )[0].item() observed_qs.append(float(lowerCAmelCase_ ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: lowerCAmelCase__ = -1 if predicted_q < threshold: lowerCAmelCase__ = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) lowerCAmelCase__ = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() lowerCAmelCase__ = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: lowerCAmelCase__ = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) test_perps.append(lowerCAmelCase_ ) print("Test perplexity, step" , lowerCAmelCase_ , ":" , lowerCAmelCase_ ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , lowerCAmelCase_ ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def _A ( ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task" ) # Required parameters parser.add_argument( "--data_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The input data dir. Should contain data files for WikiText." , ) parser.add_argument( "--model_name_or_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--data_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help=( "A jbl file containing tokenized data which can be split as objective dataset, " "train_dataset and test_dataset." ) , ) parser.add_argument( "--igf_data_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="A jbl file containing the context and information gain pairs to train secondary learner." , ) parser.add_argument( "--output_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The output directory where the final fine-tuned model is stored." , ) parser.add_argument( "--tokenizer_name" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument("--seed" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="A seed for reproducible training." ) parser.add_argument( "--context_len" , default=32 , type=lowerCAmelCase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--size_objective_set" , default=100 , type=lowerCAmelCase_ , help="number of articles that are long enough to be used as our objective set" , ) parser.add_argument( "--eval_freq" , default=100 , type=lowerCAmelCase_ , help="secondary model evaluation is triggered at eval_freq" ) parser.add_argument("--max_steps" , default=1000 , type=lowerCAmelCase_ , help="To calculate training epochs" ) parser.add_argument( "--secondary_learner_batch_size" , default=128 , type=lowerCAmelCase_ , help="batch size of training data for secondary learner" , ) parser.add_argument( "--batch_size" , default=16 , type=lowerCAmelCase_ , help="batch size of training data of language model(gpt2) " ) parser.add_argument( "--eval_interval" , default=10 , type=lowerCAmelCase_ , help=( "decay the selectivity of our secondary learner filter from" "1 standard deviation above average to 1 below average after 10 batches" ) , ) parser.add_argument( "--number" , default=100 , type=lowerCAmelCase_ , help="The number of examples split to be used as objective_set/test_data" ) parser.add_argument( "--min_len" , default=1026 , type=lowerCAmelCase_ , help="The minimum length of the article to be used as objective set" ) parser.add_argument( "--secondary_learner_max_epochs" , default=15 , type=lowerCAmelCase_ , help="number of epochs to train secondary learner" ) parser.add_argument("--trim" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="truncate the example if it exceeds context length" ) parser.add_argument( "--threshold" , default=1.0 , type=lowerCAmelCase_ , help=( "The threshold value used by secondary learner to filter the train_data and allow only" " informative data as input to the model" ) , ) parser.add_argument("--finetuned_model_name" , default="gpt2_finetuned.pt" , type=lowerCAmelCase_ , help="finetuned_model_name" ) parser.add_argument( "--recopy_model" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Reset the model to the original pretrained GPT-2 weights after each iteration" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=lowerCAmelCase_ , data_file="data/tokenized_stories_train_wikitext103.jbl" , igf_data_file="igf_context_pairs.jbl" , ) # Load train data for secondary learner lowerCAmelCase__ = joblib.load("data/IGF_values.jbl" ) # Train secondary learner lowerCAmelCase__ = training_secondary_learner( lowerCAmelCase_ , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="igf_model.pt" , ) # load pretrained gpt2 model lowerCAmelCase__ = GPTaLMHeadModel.from_pretrained("gpt2" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model lowerCAmelCase__ , lowerCAmelCase__ = generate_datasets( context_len=32 , file="data/tokenized_stories_train_wikitext103.jbl" , number=100 , min_len=1026 , trim=lowerCAmelCase_ ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=lowerCAmelCase_ , secondary_learner=lowerCAmelCase_ , eval_interval=10 , finetuned_model_name="gpt2_finetuned.pt" , ) if __name__ == "__main__": main()
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
# Copyright 2021 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 packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'adapter_config.json' UpperCamelCase = 'adapter_model.bin' UpperCamelCase = 'adapter_model.safetensors' UpperCamelCase = 'tf_model.h5' UpperCamelCase = 'tf_model.h5.index.json' UpperCamelCase = 'model.ckpt' UpperCamelCase = 'flax_model.msgpack' UpperCamelCase = 'flax_model.msgpack.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = 'config.json' UpperCamelCase = 'preprocessor_config.json' UpperCamelCase = FEATURE_EXTRACTOR_NAME UpperCamelCase = 'generation_config.json' UpperCamelCase = 'modelcard.json' UpperCamelCase = '▁' UpperCamelCase = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility UpperCamelCase = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. UpperCamelCase = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] UpperCamelCase = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" if version.parse(lowerCAmelCase_ ) < version.parse(lowerCAmelCase_ ): if "dev" in min_version: lowerCAmelCase__ = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: lowerCAmelCase__ = F'This example requires a minimum version of {min_version},' error_message += F' but the version found is {__version__}.\n' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
from math import factorial def _A ( lowerCAmelCase_ : int = 20 ): """simple docstring""" lowerCAmelCase__ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... lowerCAmelCase__ = n // 2 return int(factorial(lowerCAmelCase_ ) / (factorial(lowerCAmelCase_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCamelCase = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
import re def _A ( lowerCAmelCase_ : str ): """simple docstring""" if len(re.findall("[ATCG]" , lowerCAmelCase_ ) ) != len(lowerCAmelCase_ ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" , "TAGC" ) ) if __name__ == "__main__": import doctest doctest.testmod()
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , 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=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
1