code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyInpaintPipeline snake_case_ = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image"""] snake_case_ = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image""", ] snake_case_ = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : Optional[int] ) -> List[str]: return 32 @property def __magic_name__ ( self : List[Any] ) -> Tuple: return 32 @property def __magic_name__ ( self : Dict ) -> Optional[Any]: return self.time_input_dim @property def __magic_name__ ( self : str ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Union[str, Any] ) -> int: return 1_00 @property def __magic_name__ ( self : Dict ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] =XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def __magic_name__ ( self : Any ) -> int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) SCREAMING_SNAKE_CASE__ : List[Any] =MultilingualCLIP(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =text_encoder.eval() return text_encoder @property def __magic_name__ ( self : List[str] ) -> int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] ={ '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Dict =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Optional[Any] ) -> Dict: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : List[Any] ) -> Any: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : str =self.dummy_tokenizer SCREAMING_SNAKE_CASE__ : Dict =self.dummy_unet SCREAMING_SNAKE_CASE__ : str =self.dummy_movq SCREAMING_SNAKE_CASE__ : Any =DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.00085 , beta_end=0.012 , clip_sample=__lowercase , set_alpha_to_one=__lowercase , steps_offset=1 , prediction_type='''epsilon''' , thresholding=__lowercase , ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : Optional[Any] , __lowercase : int , __lowercase : List[str]=0 ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : str =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) # create mask SCREAMING_SNAKE_CASE__ : Optional[int] =np.ones((64, 64) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Dict =0 if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : List[str] =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : str =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : int ={ '''prompt''': '''horse''', '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] ='''cpu''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : str =output.images SCREAMING_SNAKE_CASE__ : Tuple =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : Any =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] =image_from_tuple[0, -3:, -3:, -1] print(F"image.shape {image.shape}" ) assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : int =np.array( [0.8326919, 0.73790467, 0.20918581, 0.9309612, 0.5511791, 0.43713328, 0.5513321, 0.49922934, 0.59497786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" def __magic_name__ ( self : List[str] ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : str ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : Dict =np.ones((7_68, 7_68) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : str =0 SCREAMING_SNAKE_CASE__ : Optional[Any] ='''a hat''' SCREAMING_SNAKE_CASE__ : Dict =KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-inpaint''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : Dict =pipeline( __lowercase , image=__lowercase , mask_image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
1
'''simple docstring''' import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict a_ = namedtuple( '_TestCommandArgs', [ 'dataset', 'name', 'cache_dir', 'data_dir', 'all_configs', 'save_infos', 'ignore_verifications', 'force_redownload', 'clear_cache', ], defaults=[None, None, None, False, False, False, False, False], ) def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : Tuple ): '''simple docstring''' return (abs(source - target ) / target) < 0.0_1 @pytest.mark.integration def _a( UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =_TestCommandArgs(dataset=UpperCamelCase__, all_configs=UpperCamelCase__, save_infos=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =TestCommand(*UpperCamelCase__ ) test_command.run() SCREAMING_SNAKE_CASE__ : List[Any] =os.path.join(UpperCamelCase__, '''README.md''' ) assert os.path.exists(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int =DatasetInfosDict.from_directory(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =DatasetInfosDict( { '''default''': DatasetInfo( features=Features( { '''tokens''': Sequence(Value('''string''' ) ), '''ner_tags''': Sequence( ClassLabel(names=['''O''', '''B-PER''', '''I-PER''', '''B-ORG''', '''I-ORG''', '''B-LOC''', '''I-LOC'''] ) ), '''langs''': Sequence(Value('''string''' ) ), '''spans''': Sequence(Value('''string''' ) ), } ), splits=[ { '''name''': '''train''', '''num_bytes''': 2_3_5_1_5_6_3, '''num_examples''': 1_0_0_0_0, }, { '''name''': '''validation''', '''num_bytes''': 2_3_8_4_1_8, '''num_examples''': 1_0_0_0, }, ], download_size=3_9_4_0_6_8_0, dataset_size=2_5_8_9_9_8_1, ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =getattr(dataset_infos['''default'''], UpperCamelCase__ ), getattr(expected_dataset_infos['''default'''], UpperCamelCase__ ) if key == "num_bytes": assert is_apercent_close(UpperCamelCase__, UpperCamelCase__ ) elif key == "splits": assert list(UpperCamelCase__ ) == list(UpperCamelCase__ ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes, expected[split].num_bytes ) else: result == expected
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } a_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = BertTokenizer def __init__( self : int , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : str=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Tuple="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : str=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : int =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Any =do_lower_case SCREAMING_SNAKE_CASE__ : Any =strip_accents SCREAMING_SNAKE_CASE__ : Dict =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Union[str, Any] =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =do_lower_case def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Union[str, Any]=None ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =[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 __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
1
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @require_torch def __magic_name__ ( self : Tuple ) -> Optional[Any]: # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : str =''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' SCREAMING_SNAKE_CASE__ : Any =''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' SCREAMING_SNAKE_CASE__ : Dict =''' import socket def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache SCREAMING_SNAKE_CASE__ : Dict ='''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(__lowercase ) BertModel.from_pretrained(__lowercase ) BertTokenizer.from_pretrained(__lowercase ) pipeline(task='''fill-mask''' , model=__lowercase ) # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Dict =[sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed SCREAMING_SNAKE_CASE__ : Any =self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : Any ='''1''' SCREAMING_SNAKE_CASE__ : str =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() ) @require_torch def __magic_name__ ( self : str ) -> List[Any]: # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : int =''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' SCREAMING_SNAKE_CASE__ : List[Any] =''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' SCREAMING_SNAKE_CASE__ : List[Any] =''' import socket def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(__lowercase ) BertModel.from_pretrained(__lowercase ) BertTokenizer.from_pretrained(__lowercase ) pipeline(task='''fill-mask''' , model=__lowercase ) # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Optional[Any] =[sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed SCREAMING_SNAKE_CASE__ : str =self.get_env() SCREAMING_SNAKE_CASE__ : Optional[Any] =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() ) @require_torch def __magic_name__ ( self : Any ) -> Any: # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched SCREAMING_SNAKE_CASE__ : Dict =''' from transformers import BertConfig, BertModel, BertTokenizer ''' SCREAMING_SNAKE_CASE__ : List[Any] =''' mname = "hf-internal-testing/tiny-random-bert-sharded" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print("success") ''' SCREAMING_SNAKE_CASE__ : List[Any] =''' import socket def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") socket.socket = offline_socket ''' # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : str =[sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed SCREAMING_SNAKE_CASE__ : List[Any] =self.get_env() SCREAMING_SNAKE_CASE__ : Optional[int] =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() ) # next emulate no network SCREAMING_SNAKE_CASE__ : Optional[Any] =[sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : Any ='''1''' SCREAMING_SNAKE_CASE__ : int =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() ) @require_torch def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] =''' from transformers import pipeline ''' SCREAMING_SNAKE_CASE__ : int =''' mname = "hf-internal-testing/tiny-random-bert" pipe = pipeline(model=mname) ''' SCREAMING_SNAKE_CASE__ : Optional[int] =''' import socket def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") socket.socket = offline_socket ''' SCREAMING_SNAKE_CASE__ : Any =self.get_env() SCREAMING_SNAKE_CASE__ : Tuple ='''1''' SCREAMING_SNAKE_CASE__ : Optional[int] =[sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] SCREAMING_SNAKE_CASE__ : Tuple =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( '''You cannot infer task automatically within `pipeline` when using offline mode''' , result.stderr.decode().replace('''\n''' , '''''' ) , ) @require_torch def __magic_name__ ( self : Optional[int] ) -> Any: SCREAMING_SNAKE_CASE__ : List[str] =''' from transformers import AutoModel ''' SCREAMING_SNAKE_CASE__ : List[Any] =''' mname = "hf-internal-testing/test_dynamic_model" AutoModel.from_pretrained(mname, trust_remote_code=True) print("success") ''' # baseline - just load from_pretrained with normal network SCREAMING_SNAKE_CASE__ : Optional[Any] =[sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed SCREAMING_SNAKE_CASE__ : str =self.get_env() SCREAMING_SNAKE_CASE__ : Optional[int] =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files SCREAMING_SNAKE_CASE__ : Dict ='''1''' SCREAMING_SNAKE_CASE__ : Dict =subprocess.run(__lowercase , env=__lowercase , check=__lowercase , capture_output=__lowercase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn('''success''' , result.stdout.decode() )
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( 'The `inpainting.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionInpaintPipeline` instead.' )
665
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case_ = 42 # Cache store of keys snake_case_ = 42 # References of the keys in cache snake_case_ = 10 # Maximum capacity of cache def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Any =deque() SCREAMING_SNAKE_CASE__ : str =set() if not n: SCREAMING_SNAKE_CASE__ : Optional[Any] =sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =n def __magic_name__ ( self : List[str] , __lowercase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE__ : int =self.dq_store.pop() self.key_reference.remove(__lowercase ) else: self.dq_store.remove(__lowercase ) self.dq_store.appendleft(__lowercase ) self.key_reference.add(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> None: for k in self.dq_store: print(__lowercase ) def __repr__( self : List[Any] ) -> str: return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() a_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
665
1
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
1
'''simple docstring''' from __future__ import annotations def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' if b == 0: return (1, 0) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Dict =extended_euclid(UpperCamelCase__, a % b ) SCREAMING_SNAKE_CASE__ : str =a // b return (y, x - k * y) def _a( UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Any =extended_euclid(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =na * na SCREAMING_SNAKE_CASE__ : Dict =ra * x * na + ra * y * na return (n % m + m) % m def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Dict =extended_euclid(UpperCamelCase__, UpperCamelCase__ ) if b < 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(b % n + n) % n return b def _a( UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =invert_modulo(UpperCamelCase__, UpperCamelCase__ ), invert_modulo(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =na * na SCREAMING_SNAKE_CASE__ : Dict =ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='chinese_remainder_theorem', verbose=True) testmod(name='chinese_remainder_theorem2', verbose=True) testmod(name='invert_modulo', verbose=True) testmod(name='extended_euclid', verbose=True)
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'snap-research/efficientformer-l1-300': ( 'https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """efficientformer""" def __init__( self : Optional[int] , __lowercase : List[int] = [3, 2, 6, 4] , __lowercase : List[int] = [48, 96, 2_24, 4_48] , __lowercase : List[bool] = [True, True, True, True] , __lowercase : int = 4_48 , __lowercase : int = 32 , __lowercase : int = 4 , __lowercase : int = 7 , __lowercase : int = 5 , __lowercase : int = 8 , __lowercase : int = 4 , __lowercase : float = 0.0 , __lowercase : int = 16 , __lowercase : int = 3 , __lowercase : int = 3 , __lowercase : int = 3 , __lowercase : int = 2 , __lowercase : int = 1 , __lowercase : float = 0.0 , __lowercase : int = 1 , __lowercase : bool = True , __lowercase : bool = True , __lowercase : float = 1e-5 , __lowercase : str = "gelu" , __lowercase : float = 0.02 , __lowercase : float = 1e-12 , __lowercase : int = 2_24 , __lowercase : float = 1e-05 , **__lowercase : Tuple , ) -> None: super().__init__(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_act SCREAMING_SNAKE_CASE__ : str =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =hidden_sizes SCREAMING_SNAKE_CASE__ : Any =num_hidden_layers SCREAMING_SNAKE_CASE__ : str =num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] =initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] =layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[Any] =patch_size SCREAMING_SNAKE_CASE__ : int =num_channels SCREAMING_SNAKE_CASE__ : Any =depths SCREAMING_SNAKE_CASE__ : List[str] =mlp_expansion_ratio SCREAMING_SNAKE_CASE__ : str =downsamples SCREAMING_SNAKE_CASE__ : int =dim SCREAMING_SNAKE_CASE__ : List[str] =key_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_ratio SCREAMING_SNAKE_CASE__ : Union[str, Any] =resolution SCREAMING_SNAKE_CASE__ : List[str] =pool_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =downsample_patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =downsample_stride SCREAMING_SNAKE_CASE__ : Any =downsample_pad SCREAMING_SNAKE_CASE__ : List[Any] =drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[int] =num_metaad_blocks SCREAMING_SNAKE_CASE__ : Optional[Any] =distillation SCREAMING_SNAKE_CASE__ : List[Any] =use_layer_scale SCREAMING_SNAKE_CASE__ : Optional[Any] =layer_scale_init_value SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : Tuple =batch_norm_eps
665
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
1
'''simple docstring''' from __future__ import annotations def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[int]] =[] create_all_state(1, UpperCamelCase__, UpperCamelCase__, [], UpperCamelCase__ ) return result def _a( UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : list[int], UpperCamelCase__ : list[list[int]], ): '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(UpperCamelCase__, total_number - level + 2 ): current_list.append(UpperCamelCase__ ) create_all_state(i + 1, UpperCamelCase__, level - 1, UpperCamelCase__, UpperCamelCase__ ) current_list.pop() def _a( UpperCamelCase__ : list[list[int]] ): '''simple docstring''' for i in total_list: print(*UpperCamelCase__ ) if __name__ == "__main__": a_ = 4 a_ = 2 a_ = generate_all_combinations(n, k) print_all_state(total_list)
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
1
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets a_ = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' a_ = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' a_ = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def __magic_name__ ( self : Optional[int] ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def __magic_name__ ( self : int , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =0.0 for i, j in zip(__lowercase , __lowercase ): n_correct += 1.0 if math_equivalence.is_equiv(__lowercase , __lowercase ) else 0.0 SCREAMING_SNAKE_CASE__ : str =n_correct / len(__lowercase ) return { "accuracy": accuracy, }
665
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
1
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split a_ = datasets.load_iris() a_ = np.array(data['data']) a_ = np.array(data['target']) a_ = data['target_names'] a_ , a_ , a_ , a_ = train_test_split(X, y) def _a( UpperCamelCase__ : Any, UpperCamelCase__ : List[Any] ): '''simple docstring''' return np.linalg.norm(np.array(UpperCamelCase__ ) - np.array(UpperCamelCase__ ) ) def _a( UpperCamelCase__ : str, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Any=5 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =zip(UpperCamelCase__, UpperCamelCase__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE__ : Tuple =[] for data_point in data: SCREAMING_SNAKE_CASE__ : str =euclidean_distance(data_point[0], UpperCamelCase__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE__ : Optional[Any] =[i[1] for i in sorted(UpperCamelCase__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE__ : Any =Counter(UpperCamelCase__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
665
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' def _a( UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =[redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('''All input parameters must be positive''' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('''Relative densities cannot be greater than one''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE__ : Dict =( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE__ : List[str] =hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a_ = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
665
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _a( UpperCamelCase__ : str, UpperCamelCase__ : Tuple, UpperCamelCase__ : Any, UpperCamelCase__ : List[str], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase__ ) as metadata_file: SCREAMING_SNAKE_CASE__ : Optional[int] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =LukeConfig(use_entity_aware_attention=UpperCamelCase__, **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(UpperCamelCase__, map_location='''cpu''' )['''module'''] # Load the entity vocab file SCREAMING_SNAKE_CASE__ : List[str] =load_original_entity_vocab(UpperCamelCase__ ) # add an entry for [MASK2] SCREAMING_SNAKE_CASE__ : Optional[int] =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 SCREAMING_SNAKE_CASE__ : Optional[int] =XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken('''<ent>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =AddedToken('''<ent2>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int ='''MLukeTokenizer''' with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE__ : str =tokenizer.convert_tokens_to_ids(['''@'''] )[0] SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.convert_tokens_to_ids(['''#'''] )[0] SCREAMING_SNAKE_CASE__ : Dict =state_dict['''embeddings.word_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : List[str] =word_emb[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Tuple =word_emb[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[bias_name] SCREAMING_SNAKE_CASE__ : List[Any] =decoder_bias[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =decoder_bias[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE__ : Tuple =f"encoder.layer.{layer_index}.attention.self." SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : List[Any] =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE__ : Any =state_dict['''entity_embeddings.entity_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : Any =entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict['''entity_predictions.bias'''] SCREAMING_SNAKE_CASE__ : Tuple =entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_prediction_bias, entity_mask_bias] ) SCREAMING_SNAKE_CASE__ : int =LukeForMaskedLM(config=UpperCamelCase__ ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) SCREAMING_SNAKE_CASE__ : Tuple =OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[key] else: SCREAMING_SNAKE_CASE__ : Any =state_dict[key] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if set(UpperCamelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(f"Unexpected unexpected_keys: {unexpected_keys}" ) if set(UpperCamelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs SCREAMING_SNAKE_CASE__ : Any =MLukeTokenizer.from_pretrained(UpperCamelCase__, task='''entity_classification''' ) SCREAMING_SNAKE_CASE__ : str ='''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =(0, 9) SCREAMING_SNAKE_CASE__ : str =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =model(**UpperCamelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : str =torch.Size((1, 3_3, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : Any =torch.Size((1, 1, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" f" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify masked word/entity prediction SCREAMING_SNAKE_CASE__ : str =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''Tokyo is the capital of <mask>.''' SCREAMING_SNAKE_CASE__ : Dict =(2_4, 3_0) SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[str] =model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =encoding['''input_ids'''][0].tolist() SCREAMING_SNAKE_CASE__ : Any =input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.entity_logits[0][0].argmax().item() SCREAMING_SNAKE_CASE__ : Dict =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(UpperCamelCase__ ) ) model.save_pretrained(UpperCamelCase__ ) def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =['''[MASK]''', '''[PAD]''', '''[UNK]'''] SCREAMING_SNAKE_CASE__ : List[str] =[json.loads(UpperCamelCase__ ) for line in open(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Optional[int] ={} for entry in data: SCREAMING_SNAKE_CASE__ : Tuple =entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: SCREAMING_SNAKE_CASE__ : str =entity_id break SCREAMING_SNAKE_CASE__ : Union[str, Any] =f"{language}:{entity_name}" SCREAMING_SNAKE_CASE__ : Union[str, Any] =entity_id return new_mapping if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a_ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
665
1
'''simple docstring''' from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase ): snake_case_ = """pixel_values""" snake_case_ = False snake_case_ = TimmBackboneConfig def __init__( self : Union[str, Any] , __lowercase : Optional[Any] , **__lowercase : Optional[int] ) -> Any: requires_backends(self , '''timm''' ) super().__init__(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =config if config.backbone is None: raise ValueError('''backbone is not set in the config. Please set it to a timm model name.''' ) if config.backbone not in timm.list_models(): raise ValueError(F"backbone {config.backbone} is not supported by timm." ) if hasattr(__lowercase , '''out_features''' ) and config.out_features is not None: raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.''' ) SCREAMING_SNAKE_CASE__ : Any =getattr(__lowercase , '''use_pretrained_backbone''' , __lowercase ) if pretrained is None: raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.''' ) # We just take the final layer by default. This matches the default for the transformers models. SCREAMING_SNAKE_CASE__ : Optional[int] =config.out_indices if getattr(__lowercase , '''out_indices''' , __lowercase ) is not None else (-1,) SCREAMING_SNAKE_CASE__ : str =timm.create_model( config.backbone , pretrained=__lowercase , features_only=config.features_only , in_chans=config.num_channels , out_indices=__lowercase , **__lowercase , ) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. SCREAMING_SNAKE_CASE__ : List[str] =self._backbone.return_layers SCREAMING_SNAKE_CASE__ : List[Any] ={layer['''module''']: str(__lowercase ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(__lowercase ) @classmethod def __magic_name__ ( cls : str , __lowercase : Optional[Any] , *__lowercase : str , **__lowercase : Optional[Any] ) -> Dict: requires_backends(cls , ['''vision''', '''timm'''] ) from ...models.timm_backbone import TimmBackboneConfig SCREAMING_SNAKE_CASE__ : Optional[int] =kwargs.pop('''config''' , TimmBackboneConfig() ) SCREAMING_SNAKE_CASE__ : str =kwargs.pop('''use_timm_backbone''' , __lowercase ) if not use_timm: raise ValueError('''use_timm_backbone must be True for timm backbones''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =kwargs.pop('''num_channels''' , config.num_channels ) SCREAMING_SNAKE_CASE__ : Tuple =kwargs.pop('''features_only''' , config.features_only ) SCREAMING_SNAKE_CASE__ : str =kwargs.pop('''use_pretrained_backbone''' , config.use_pretrained_backbone ) SCREAMING_SNAKE_CASE__ : Any =kwargs.pop('''out_indices''' , config.out_indices ) SCREAMING_SNAKE_CASE__ : List[Any] =TimmBackboneConfig( backbone=__lowercase , num_channels=__lowercase , features_only=__lowercase , use_pretrained_backbone=__lowercase , out_indices=__lowercase , ) return super()._from_config(__lowercase , **__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : str ) -> str: pass def __magic_name__ ( self : Tuple , __lowercase : Tuple , __lowercase : int=None , __lowercase : Optional[int]=None , __lowercase : List[str]=None , **__lowercase : Dict ) -> Union[BackboneOutput, Tuple[Tensor, ...]]: SCREAMING_SNAKE_CASE__ : Optional[Any] =return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ : Optional[Any] =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ : List[Any] =output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError('''Cannot output attentions for timm backbones at the moment''' ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone SCREAMING_SNAKE_CASE__ : Optional[int] =self._all_layers SCREAMING_SNAKE_CASE__ : str =self._backbone(__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self._return_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =tuple(hidden_states[i] for i in self.out_indices ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self._backbone(__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =None SCREAMING_SNAKE_CASE__ : Tuple =tuple(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =tuple(__lowercase ) if hidden_states is not None else None if not return_dict: SCREAMING_SNAKE_CASE__ : Dict =(feature_maps,) if output_hidden_states: SCREAMING_SNAKE_CASE__ : Dict =output + (hidden_states,) return output return BackboneOutput(feature_maps=__lowercase , hidden_states=__lowercase , attentions=__lowercase )
665
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : List[Any] =True for i in range(UpperCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE__ : Optional[int] =True if a[i].islower(): SCREAMING_SNAKE_CASE__ : List[Any] =True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase ): @register_to_config def __init__( self : Optional[int] , *, __lowercase : int = 4 , __lowercase : int = 7_68 , __lowercase : int , __lowercase : Dict , ) -> Tuple: super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] =nn.Parameter(torch.zeros(__lowercase ) ) # parameters for additional clip time embeddings SCREAMING_SNAKE_CASE__ : Dict =nn.Linear(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =nn.Linear(__lowercase , __lowercase ) # parameters for encoder hidden states SCREAMING_SNAKE_CASE__ : Tuple =clip_extra_context_tokens SCREAMING_SNAKE_CASE__ : str =nn.Linear( __lowercase , self.clip_extra_context_tokens * cross_attention_dim ) SCREAMING_SNAKE_CASE__ : List[str] =nn.Linear(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =nn.LayerNorm(__lowercase ) def __magic_name__ ( self : Optional[int] , *, __lowercase : Optional[int] , __lowercase : Any , __lowercase : str , __lowercase : List[Any] ) -> Tuple: if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings SCREAMING_SNAKE_CASE__ : List[Any] =image_embeddings.shape[0] SCREAMING_SNAKE_CASE__ : Any =self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =classifier_free_guidance_embeddings.expand( __lowercase , -1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] SCREAMING_SNAKE_CASE__ : Dict =prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... SCREAMING_SNAKE_CASE__ : Optional[int] =self.embedding_proj(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.clip_image_embeddings_project_to_time_embeddings(__lowercase ) SCREAMING_SNAKE_CASE__ : str =time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" SCREAMING_SNAKE_CASE__ : Tuple =self.clip_extra_context_tokens_proj(__lowercase ) SCREAMING_SNAKE_CASE__ : str =clip_extra_context_tokens.reshape(__lowercase , -1 , self.clip_extra_context_tokens ) SCREAMING_SNAKE_CASE__ : Optional[Any] =clip_extra_context_tokens.permute(0 , 2 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.encoder_hidden_states_proj(__lowercase ) SCREAMING_SNAKE_CASE__ : str =self.text_encoder_hidden_states_norm(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
665
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[Any] , __lowercase : List[str]=13 , __lowercase : int=7 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : List[Any]=True , __lowercase : str=True , __lowercase : Tuple=99 , __lowercase : Union[str, Any]=64 , __lowercase : Tuple=32 , __lowercase : Optional[Any]=5 , __lowercase : Tuple=4 , __lowercase : Optional[int]=37 , __lowercase : int="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : List[Any]=0.1 , __lowercase : List[Any]=5_12 , __lowercase : int=16 , __lowercase : Optional[int]=2 , __lowercase : Tuple=0.02 , __lowercase : List[str]=3 , __lowercase : List[str]=4 , __lowercase : List[str]=None , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =seq_length SCREAMING_SNAKE_CASE__ : Dict =is_training SCREAMING_SNAKE_CASE__ : List[Any] =use_input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] =use_labels SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : str =hidden_size SCREAMING_SNAKE_CASE__ : Any =embedding_size SCREAMING_SNAKE_CASE__ : Tuple =num_hidden_layers SCREAMING_SNAKE_CASE__ : str =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : Any =type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE__ : str =num_labels SCREAMING_SNAKE_CASE__ : List[str] =num_choices SCREAMING_SNAKE_CASE__ : List[str] =scope def __magic_name__ ( self : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : int =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =None SCREAMING_SNAKE_CASE__ : Optional[Any] =None SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : List[str] ) -> Any: return MegatronBertConfig( 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 , embedding_size=self.embedding_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=__lowercase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Any , __lowercase : Tuple , __lowercase : Any , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ ( self : Dict , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : Any , __lowercase : Optional[int] , __lowercase : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =MegatronBertForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : List[str] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : str , __lowercase : Any , __lowercase : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =MegatronBertForNextSentencePrediction(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : List[str] , __lowercase : Optional[int] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForPreTraining(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , next_sentence_label=__lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any , __lowercase : Any , __lowercase : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =MegatronBertForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __magic_name__ ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : int , __lowercase : List[str] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.num_labels SCREAMING_SNAKE_CASE__ : Dict =MegatronBertForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple =self.num_labels SCREAMING_SNAKE_CASE__ : int =MegatronBertForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : Dict , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Any , __lowercase : List[Any] , __lowercase : int , __lowercase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.num_choices SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[int] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : str ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True # test_resize_embeddings = False snake_case_ = False def __magic_name__ ( self : List[Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : Tuple=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str ) -> Dict: self.config_tester.run_common_tests() def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowercase ) def __magic_name__ ( self : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowercase ) def __magic_name__ ( self : Dict ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowercase ) def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' return torch.tensor( UpperCamelCase__, dtype=torch.long, device=UpperCamelCase__, ) a_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow @unittest.skip('''Model is not available.''' ) def __magic_name__ ( self : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any ='''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ : Optional[int] =os.path.join(os.environ['''MYDIR'''] , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =MegatronBertModel.from_pretrained(__lowercase ) model.to(__lowercase ) model.half() SCREAMING_SNAKE_CASE__ : Dict =_long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase )[0] SCREAMING_SNAKE_CASE__ : Dict =torch.Size((1, 9, 10_24) ) self.assertEqual(output.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : str =[-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ : List[Any] =output[0, ii, jj] SCREAMING_SNAKE_CASE__ : Tuple =expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ : List[str] ='''ii={} jj={} a={} b={}'''.format(__lowercase , __lowercase , __lowercase , __lowercase ) self.assertTrue(math.isclose(__lowercase , __lowercase , rel_tol=__lowercase , abs_tol=__lowercase ) , msg=__lowercase )
665
1
'''simple docstring''' from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __SCREAMING_SNAKE_CASE : pass
665
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() SCREAMING_SNAKE_CASE__ : List[str] =[sys.executable] + distributed_args execute_subprocess_async(__lowercase , env=os.environ.copy() )
665
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a_ = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = ShapEImgaImgPipeline snake_case_ = ["""image"""] snake_case_ = ["""image"""] snake_case_ = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[Any] ) -> List[Any]: return 32 @property def __magic_name__ ( self : List[str] ) -> Optional[int]: return 32 @property def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: return self.time_input_dim * 4 @property def __magic_name__ ( self : Dict ) -> Union[str, Any]: return 8 @property def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) SCREAMING_SNAKE_CASE__ : str =CLIPVisionModel(__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =CLIPImageProcessor( crop_size=2_24 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __magic_name__ ( self : List[str] ) -> Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str ={ '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } SCREAMING_SNAKE_CASE__ : str =PriorTransformer(**__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE__ : str =ShapERenderer(**__lowercase ) return model def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.dummy_prior SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_encoder SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_processor SCREAMING_SNAKE_CASE__ : Tuple =self.dummy_renderer SCREAMING_SNAKE_CASE__ : int =HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=__lowercase , clip_sample=__lowercase , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ : Any ={ '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __magic_name__ ( self : Any , __lowercase : List[str] , __lowercase : Any=0 ) -> Any: SCREAMING_SNAKE_CASE__ : int =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : List[str] =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : List[str] ) -> str: SCREAMING_SNAKE_CASE__ : int ='''cpu''' SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : str =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] =np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __magic_name__ ( self : List[Any] ) -> List[str]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch_device == '''cpu''' SCREAMING_SNAKE_CASE__ : Optional[Any] =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowercase , relax_max_difference=__lowercase , ) def __magic_name__ ( self : Dict ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =1 SCREAMING_SNAKE_CASE__ : List[str] =2 SCREAMING_SNAKE_CASE__ : Dict =self.get_dummy_inputs(__lowercase ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ : Tuple =batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ : List[Any] =pipe(**__lowercase , num_images_per_prompt=__lowercase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Optional[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) SCREAMING_SNAKE_CASE__ : Dict =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) SCREAMING_SNAKE_CASE__ : List[Any] =ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) SCREAMING_SNAKE_CASE__ : Tuple =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple =pipe( __lowercase , generator=__lowercase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } a_ = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =collections.OrderedDict() with open(UpperCamelCase__, '''r''', encoding='''utf-8''' ) as reader: SCREAMING_SNAKE_CASE__ : Any =reader.readlines() for index, token in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : str =token.rstrip('''\n''' ) SCREAMING_SNAKE_CASE__ : Any =index return vocab class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Optional[int] , __lowercase : Optional[Any] , __lowercase : Tuple="<unk>" , __lowercase : Any=2_00 ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[Any] =vocab SCREAMING_SNAKE_CASE__ : int =unk_token SCREAMING_SNAKE_CASE__ : List[Any] =max_input_chars_per_word def __magic_name__ ( self : List[Any] , __lowercase : Any ) -> Dict: SCREAMING_SNAKE_CASE__ : str =list(__lowercase ) if len(__lowercase ) > self.max_input_chars_per_word: return [self.unk_token] SCREAMING_SNAKE_CASE__ : Dict =0 SCREAMING_SNAKE_CASE__ : List[str] =[] while start < len(__lowercase ): SCREAMING_SNAKE_CASE__ : Tuple =len(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =None while start < end: SCREAMING_SNAKE_CASE__ : Optional[int] =''''''.join(chars[start:end] ) if substr in self.vocab: SCREAMING_SNAKE_CASE__ : List[str] =substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =end return sub_tokens class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): 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_ = False def __init__( self : List[Any] , __lowercase : Union[str, Any] , __lowercase : List[Any]="<d>" , __lowercase : Optional[int]="</d>" , __lowercase : List[str]="<s>" , __lowercase : Any="</s>" , __lowercase : Tuple="<pad>" , __lowercase : Tuple="<unk>" , __lowercase : str="</n>" , __lowercase : Optional[Any]="</_>" , __lowercase : str="left" , **__lowercase : str , ) -> Optional[Any]: requires_backends(self , ['''jieba'''] ) super().__init__( bod_token=__lowercase , eod_token=__lowercase , bos_token=__lowercase , eos_token=__lowercase , pad_token=__lowercase , unk_token=__lowercase , line_token=__lowercase , space_token=__lowercase , padding_side=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =bod_token SCREAMING_SNAKE_CASE__ : List[Any] =eod_token SCREAMING_SNAKE_CASE__ : Optional[int] =load_vocab(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =self.encoder[space_token] SCREAMING_SNAKE_CASE__ : List[Any] =self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] SCREAMING_SNAKE_CASE__ : Union[str, Any] =collections.OrderedDict(sorted(self.encoder.items() , key=lambda __lowercase : x[1] ) ) SCREAMING_SNAKE_CASE__ : List[str] ={v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE__ : str =WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def __magic_name__ ( self : Optional[Any] ) -> Dict: return self.encoder[self.bod_token] @property def __magic_name__ ( self : Union[str, Any] ) -> Dict: return self.encoder[self.eod_token] @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return self.encoder["\n"] @property def __magic_name__ ( self : List[str] ) -> int: return len(self.encoder ) def __magic_name__ ( self : int ) -> List[Any]: return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] ) -> int: SCREAMING_SNAKE_CASE__ : List[Any] =[] for x in jieba.cut(__lowercase , cut_all=__lowercase ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__lowercase ) ) return output_tokens def __magic_name__ ( self : Dict , __lowercase : Union[str, Any] , **__lowercase : Union[str, Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] =[i for i in token_ids if i >= 0] SCREAMING_SNAKE_CASE__ : Any =[ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__lowercase , **__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : Any ) -> int: return token in self.encoder def __magic_name__ ( self : int , __lowercase : List[str] ) -> str: return "".join(__lowercase ) def __magic_name__ ( self : List[Any] , __lowercase : List[Any] ) -> List[Any]: return self.encoder.get(__lowercase , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , __lowercase : List[Any] ) -> Union[str, Any]: return self.decoder.get(__lowercase , self.unk_token ) def __magic_name__ ( self : Any , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: if os.path.isdir(__lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: SCREAMING_SNAKE_CASE__ : Dict =(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 if " " in self.encoder: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.encoder[''' '''] del self.encoder[" "] if "\n" in self.encoder: SCREAMING_SNAKE_CASE__ : int =self.encoder['''\n'''] del self.encoder["\n"] SCREAMING_SNAKE_CASE__ : Optional[Any] =collections.OrderedDict(sorted(self.encoder.items() , key=lambda __lowercase : x[1] ) ) with open(__lowercase , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ''' Please check that the vocabulary is not corrupted!''' ) SCREAMING_SNAKE_CASE__ : int =token_index writer.write(token + '''\n''' ) index += 1 return (vocab_file,) def __magic_name__ ( self : Optional[int] , __lowercase : List[int] , __lowercase : List[int] = None ) -> List[int]: if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def __magic_name__ ( self : Optional[Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None , __lowercase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is not None: return [1] + ([0] * len(__lowercase )) + [1] + ([0] * len(__lowercase )) return [1] + ([0] * len(__lowercase ))
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_bigcode""" snake_case_ = ["""past_key_values"""] snake_case_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Any , __lowercase : Any=5_02_57 , __lowercase : int=10_24 , __lowercase : List[str]=7_68 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : List[str]=None , __lowercase : int="gelu_pytorch_tanh" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=1e-5 , __lowercase : List[str]=0.02 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=5_02_56 , __lowercase : List[Any]=5_02_56 , __lowercase : Union[str, Any]=True , __lowercase : List[str]=True , __lowercase : Dict=True , **__lowercase : List[Any] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_positions SCREAMING_SNAKE_CASE__ : Dict =n_embd SCREAMING_SNAKE_CASE__ : Dict =n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_head SCREAMING_SNAKE_CASE__ : List[str] =n_inner SCREAMING_SNAKE_CASE__ : List[str] =activation_function SCREAMING_SNAKE_CASE__ : List[Any] =resid_pdrop SCREAMING_SNAKE_CASE__ : List[Any] =embd_pdrop SCREAMING_SNAKE_CASE__ : List[str] =attn_pdrop SCREAMING_SNAKE_CASE__ : Dict =layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =scale_attn_weights SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Dict =attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : int =scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Dict =multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] =eos_token_id super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase )
665
1
'''simple docstring''' import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor a_ = logging.getLogger(__name__) a_ = 5_0 # max width of layer names a_ = 7_0 # max width of quantizer names def _a( UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =parser.add_argument_group('''quant_trainer arguments''' ) group.add_argument('''--wprec''', type=UpperCamelCase__, default=8, help='''weight precision''' ) group.add_argument('''--aprec''', type=UpperCamelCase__, default=8, help='''activation precision''' ) group.add_argument('''--quant-per-tensor''', action='''store_true''', help='''per tensor weight scaling''' ) group.add_argument('''--quant-disable''', action='''store_true''', help='''disable all quantizers''' ) group.add_argument('''--quant-disable-embeddings''', action='''store_true''', help='''disable all embeddings quantizers''' ) group.add_argument('''--quant-disable-keyword''', type=UpperCamelCase__, nargs='''+''', help='''disable quantizers by keyword''' ) group.add_argument('''--quant-disable-layer-module''', type=UpperCamelCase__, help='''disable quantizers by keyword under layer.''' ) group.add_argument('''--quant-enable-layer-module''', type=UpperCamelCase__, help='''enable quantizers by keyword under layer''' ) group.add_argument('''--calibrator''', default='''max''', help='''which quantization range calibrator to use''' ) group.add_argument('''--percentile''', default=UpperCamelCase__, type=UpperCamelCase__, help='''percentile for PercentileCalibrator''' ) group.add_argument('''--fuse-qkv''', action='''store_true''', help='''use the same scale factor for qkv''' ) group.add_argument('''--clip-gelu''', metavar='''N''', type=UpperCamelCase__, help='''clip gelu output maximum value to N''' ) group.add_argument( '''--recalibrate-weights''', action='''store_true''', help=( '''recalibrate weight amaxes by taking the max of the weights.''' ''' amaxes will be computed with the current quantization granularity (axis).''' ), ) def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' if args.calibrator == "max": SCREAMING_SNAKE_CASE__ : List[Any] ='''max''' elif args.calibrator == "percentile": if args.percentile is None: raise ValueError('''Specify --percentile when using percentile calibrator''' ) SCREAMING_SNAKE_CASE__ : List[str] ='''histogram''' elif args.calibrator == "mse": SCREAMING_SNAKE_CASE__ : Tuple ='''histogram''' else: raise ValueError(f"Invalid calibrator {args.calibrator}" ) SCREAMING_SNAKE_CASE__ : Optional[Any] =QuantDescriptor(num_bits=args.aprec, calib_method=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =QuantDescriptor(num_bits=args.wprec, axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(UpperCamelCase__ ) quant_nn.QuantLinear.set_default_quant_desc_weight(UpperCamelCase__ ) def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : int, UpperCamelCase__ : List[str]=False, UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' logger.info('''Configuring Model for Quantization''' ) logger.info(f"using quantization package {pytorch_quantization.__file__}" ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(UpperCamelCase__, ['''embeddings'''], which='''weight''', _disabled=UpperCamelCase__ ) if args.quant_disable: set_quantizer_by_name(UpperCamelCase__, [''''''], _disabled=UpperCamelCase__ ) if args.quant_disable_keyword: set_quantizer_by_name(UpperCamelCase__, args.quant_disable_keyword, _disabled=UpperCamelCase__ ) if args.quant_disable_layer_module: set_quantizer_by_name(UpperCamelCase__, [R'''layer.\d+.''' + args.quant_disable_layer_module], _disabled=UpperCamelCase__ ) if args.quant_enable_layer_module: set_quantizer_by_name(UpperCamelCase__, [R'''layer.\d+.''' + args.quant_enable_layer_module], _disabled=UpperCamelCase__ ) if args.recalibrate_weights: recalibrate_weights(UpperCamelCase__ ) if args.fuse_qkv: fuse_qkv(UpperCamelCase__, UpperCamelCase__ ) if args.clip_gelu: clip_gelu(UpperCamelCase__, args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(UpperCamelCase__ ) def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' logger.info('''Enabling Calibration''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(f"{name:80}: {module}" ) def _a( UpperCamelCase__ : Any, UpperCamelCase__ : int ): '''simple docstring''' logger.info('''Loading calibrated amax''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: if isinstance(module._calibrator, calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax('''percentile''', percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(UpperCamelCase__ ) def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[int] ): '''simple docstring''' def fusea(UpperCamelCase__ : Any, UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any] ): for mod in [qq, qk, qv]: if not hasattr(UpperCamelCase__, '''_amax''' ): print(''' WARNING: NO AMAX BUFFER''' ) return SCREAMING_SNAKE_CASE__ : Any =qq._amax.detach().item() SCREAMING_SNAKE_CASE__ : Union[str, Any] =qk._amax.detach().item() SCREAMING_SNAKE_CASE__ : str =qv._amax.detach().item() SCREAMING_SNAKE_CASE__ : int =max(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) qq._amax.fill_(UpperCamelCase__ ) qk._amax.fill_(UpperCamelCase__ ) qv._amax.fill_(UpperCamelCase__ ) logger.info(f" q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}" ) for name, mod in model.named_modules(): if name.endswith('''.attention.self''' ): logger.info(f"FUSE_QKV: {name:{name_width}}" ) fusea(mod.matmul_q_input_quantizer, mod.matmul_k_input_quantizer, mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer, mod.key._weight_quantizer, mod.value._weight_quantizer ) def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Dict ): '''simple docstring''' for name, mod in model.named_modules(): if name.endswith('''.output.dense''' ) and not name.endswith('''attention.output.dense''' ): SCREAMING_SNAKE_CASE__ : Tuple =mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =mod._input_quantizer._amax.data.detach().item() logger.info(f"CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}" ) def _a( UpperCamelCase__ : List[Any] ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(UpperCamelCase__, '''_weight_quantizer''' ) and mod._weight_quantizer.axis is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =mod.weight.shape[0] SCREAMING_SNAKE_CASE__ : Any =mod._weight_quantizer._amax.detach() SCREAMING_SNAKE_CASE__ : str =torch.ones(UpperCamelCase__, dtype=amax.dtype, device=amax.device ) * amax print(f"expanding {name} {amax} -> {mod._weight_quantizer._amax}" ) def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(UpperCamelCase__, '''_weight_quantizer''' ): if not hasattr(mod.weight_quantizer, '''_amax''' ): print('''RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER''' ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) SCREAMING_SNAKE_CASE__ : Dict =set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) SCREAMING_SNAKE_CASE__ : List[Any] =set(range(len(mod.weight.size() ) ) ) - axis_set SCREAMING_SNAKE_CASE__ : int =pytorch_quantization.utils.reduce_amax(mod.weight, axis=UpperCamelCase__, keepdims=UpperCamelCase__ ).detach() logger.info(f"RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}" ) SCREAMING_SNAKE_CASE__ : str =amax def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Optional[int]=2_5, UpperCamelCase__ : Dict=1_8_0, UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' if ignore is None: SCREAMING_SNAKE_CASE__ : str =[] elif not isinstance(UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Dict =[ignore] SCREAMING_SNAKE_CASE__ : Tuple =0 for name, mod in model.named_modules(): if not hasattr(UpperCamelCase__, '''weight''' ): continue SCREAMING_SNAKE_CASE__ : Tuple =max(UpperCamelCase__, len(UpperCamelCase__ ) ) for name, mod in model.named_modules(): SCREAMING_SNAKE_CASE__ : Optional[Any] =getattr(UpperCamelCase__, '''_input_quantizer''', UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =getattr(UpperCamelCase__, '''_weight_quantizer''', UpperCamelCase__ ) if not hasattr(UpperCamelCase__, '''weight''' ): continue if type(UpperCamelCase__ ) in ignore: continue if [True for s in ignore if type(UpperCamelCase__ ) is str and s in name]: continue SCREAMING_SNAKE_CASE__ : Any =f"Act:{input_q.extra_repr()}" SCREAMING_SNAKE_CASE__ : List[str] =f"Wgt:{weight_q.extra_repr()}" SCREAMING_SNAKE_CASE__ : str =f"{name:{name_width}} {act_str} {wgt_str}" if len(UpperCamelCase__ ) <= line_width: logger.info(UpperCamelCase__ ) else: logger.info(f"{name:{name_width}} {act_str}" ) logger.info(f"{' ':{name_width}} {wgt_str}" ) def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for name, mod in model.named_modules(): if isinstance(UpperCamelCase__, pytorch_quantization.nn.TensorQuantizer ): print(f"{name:80} {mod}" ) count += 1 print(f"{count} TensorQuantizers found in model" ) def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : int, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =getattr(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) if quantizer_mod is not None: assert hasattr(UpperCamelCase__, UpperCamelCase__ ) setattr(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: logger.warning(f"{name} has no {quantizer}" ) def _a( UpperCamelCase__ : Dict, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : int="both", **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =f"Warning: changing {which} quantizers of {name:{qname_width}}" for k, v in kwargs.items(): s += f" {k}={v}" if which in ["input", "both"]: set_quantizer(UpperCamelCase__, UpperCamelCase__, '''_input_quantizer''', UpperCamelCase__, UpperCamelCase__ ) if which in ["weight", "both"]: set_quantizer(UpperCamelCase__, UpperCamelCase__, '''_weight_quantizer''', UpperCamelCase__, UpperCamelCase__ ) logger.info(UpperCamelCase__ ) def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Any, **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(UpperCamelCase__, '''_input_quantizer''' ) or hasattr(UpperCamelCase__, '''_weight_quantizer''' ): for n in names: if re.search(UpperCamelCase__, UpperCamelCase__ ): set_quantizers(UpperCamelCase__, UpperCamelCase__, **UpperCamelCase__ ) elif name.endswith('''_quantizer''' ): for n in names: if re.search(UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Dict =f"Warning: changing {name:{name_width}}" for k, v in kwargs.items(): s += f" {k}={v}" setattr(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) logger.info(UpperCamelCase__ )
665
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =size SCREAMING_SNAKE_CASE__ : List[Any] =[0] * size SCREAMING_SNAKE_CASE__ : str =[0] * size @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return index | (index + 1) @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return (index & (index + 1)) - 1 def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =value while index < self.size: SCREAMING_SNAKE_CASE__ : Any =self.get_prev(__lowercase ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : List[str] =value else: SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_next(__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> int: right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : str =0 while left <= right: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_prev(__lowercase ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[Any] =max(__lowercase , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Any =current_left else: SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a_ = logging.get_logger(__name__) a_ = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a_ = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] a_ = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """whisper""" snake_case_ = ["""past_key_values"""] snake_case_ = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Any , __lowercase : Any=5_18_65 , __lowercase : Optional[Any]=80 , __lowercase : Union[str, Any]=6 , __lowercase : Optional[int]=4 , __lowercase : Optional[int]=6 , __lowercase : int=4 , __lowercase : Dict=15_36 , __lowercase : Any=15_36 , __lowercase : Dict=0.0 , __lowercase : Dict=0.0 , __lowercase : Optional[int]=5_02_57 , __lowercase : Optional[int]=True , __lowercase : List[str]=True , __lowercase : Optional[int]="gelu" , __lowercase : Dict=2_56 , __lowercase : Union[str, Any]=0.0 , __lowercase : Optional[int]=0.0 , __lowercase : Optional[Any]=0.0 , __lowercase : Any=0.02 , __lowercase : Optional[Any]=False , __lowercase : int=15_00 , __lowercase : Any=4_48 , __lowercase : int=5_02_56 , __lowercase : Dict=5_02_56 , __lowercase : Dict=5_02_56 , __lowercase : List[Any]=None , __lowercase : Tuple=[2_20, 5_02_56] , __lowercase : Dict=False , __lowercase : Dict=2_56 , __lowercase : List[Any]=False , __lowercase : Union[str, Any]=0.05 , __lowercase : List[Any]=10 , __lowercase : List[str]=2 , __lowercase : Dict=0.0 , __lowercase : int=10 , __lowercase : Any=0 , __lowercase : int=7 , **__lowercase : int , ) -> List[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =vocab_size SCREAMING_SNAKE_CASE__ : int =num_mel_bins SCREAMING_SNAKE_CASE__ : Optional[int] =d_model SCREAMING_SNAKE_CASE__ : Optional[int] =encoder_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =encoder_attention_heads SCREAMING_SNAKE_CASE__ : str =decoder_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =decoder_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[int] =encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] =dropout SCREAMING_SNAKE_CASE__ : Optional[int] =attention_dropout SCREAMING_SNAKE_CASE__ : str =activation_dropout SCREAMING_SNAKE_CASE__ : str =activation_function SCREAMING_SNAKE_CASE__ : Tuple =init_std SCREAMING_SNAKE_CASE__ : List[str] =encoder_layerdrop SCREAMING_SNAKE_CASE__ : int =decoder_layerdrop SCREAMING_SNAKE_CASE__ : List[Any] =use_cache SCREAMING_SNAKE_CASE__ : Union[str, Any] =encoder_layers SCREAMING_SNAKE_CASE__ : List[str] =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE__ : Any =max_source_positions SCREAMING_SNAKE_CASE__ : List[str] =max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE__ : List[Any] =classifier_proj_size SCREAMING_SNAKE_CASE__ : List[str] =use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE__ : List[str] =apply_spec_augment SCREAMING_SNAKE_CASE__ : str =mask_time_prob SCREAMING_SNAKE_CASE__ : List[str] =mask_time_length SCREAMING_SNAKE_CASE__ : int =mask_time_min_masks SCREAMING_SNAKE_CASE__ : Any =mask_feature_prob SCREAMING_SNAKE_CASE__ : List[str] =mask_feature_length SCREAMING_SNAKE_CASE__ : int =mask_feature_min_masks SCREAMING_SNAKE_CASE__ : Optional[int] =median_filter_width super().__init__( pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , is_encoder_decoder=__lowercase , decoder_start_token_id=__lowercase , suppress_tokens=__lowercase , begin_suppress_tokens=__lowercase , **__lowercase , ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @property def __magic_name__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: SCREAMING_SNAKE_CASE__ : Optional[Any] =OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: SCREAMING_SNAKE_CASE__ : List[str] ={0: '''batch'''} else: SCREAMING_SNAKE_CASE__ : Union[str, Any] ={0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__lowercase , direction='''inputs''' ) return common_inputs def __magic_name__ ( self : int , __lowercase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional["TensorType"] = None , __lowercase : int = 2_20_50 , __lowercase : float = 5.0 , __lowercase : int = 2_20 , ) -> Mapping[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =OrderedDict() SCREAMING_SNAKE_CASE__ : Optional[int] =OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=__lowercase , framework=__lowercase , sampling_rate=__lowercase , time_duration=__lowercase , frequency=__lowercase , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =encoder_inputs['''input_features'''].shape[2] SCREAMING_SNAKE_CASE__ : List[Any] =encoder_sequence_length // 2 if self.use_past else seq_length SCREAMING_SNAKE_CASE__ : Any =super().generate_dummy_inputs( preprocessor.tokenizer , __lowercase , __lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =encoder_inputs.pop('''input_features''' ) SCREAMING_SNAKE_CASE__ : List[str] =decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: SCREAMING_SNAKE_CASE__ : Union[str, Any] =decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __magic_name__ ( self : Dict ) -> float: return 1e-3
665
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""vqvae"""] def __init__( self : int , __lowercase : AutoencoderKL , __lowercase : UNetaDConditionModel , __lowercase : Mel , __lowercase : Union[DDIMScheduler, DDPMScheduler] , ) -> int: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase , mel=__lowercase , vqvae=__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return 50 if isinstance(self.scheduler , __lowercase ) else 10_00 @torch.no_grad() def __call__( self : Dict , __lowercase : int = 1 , __lowercase : str = None , __lowercase : np.ndarray = None , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = None , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : float = 0 , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : torch.Tensor = None , __lowercase : torch.Tensor = None , __lowercase : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: SCREAMING_SNAKE_CASE__ : Optional[Any] =steps or self.get_default_steps() self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE__ : Optional[int] =randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowercase , device=self.device , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =noise SCREAMING_SNAKE_CASE__ : List[str] =None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.mel.audio_slice_to_image(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE__ : int =(input_image / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =self.vqvae.encode(torch.unsqueeze(__lowercase , 0 ) ).latent_dist.sample( generator=__lowercase )[0] SCREAMING_SNAKE_CASE__ : int =self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE__ : Optional[Any] =int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : Tuple =int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowercase ): SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase , __lowercase )['''sample'''] else: SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase )['''sample'''] if isinstance(self.scheduler , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , eta=__lowercase , generator=__lowercase , )['''prev_sample'''] else: SCREAMING_SNAKE_CASE__ : Any =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , generator=__lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE__ : List[str] =mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE__ : str =1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE__ : int =self.vqvae.decode(__lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE__ : Dict =(images * 2_55).round().astype('''uint8''' ) SCREAMING_SNAKE_CASE__ : Any =list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[self.mel.image_to_audio(__lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowercase ) ) @torch.no_grad() def __magic_name__ ( self : Optional[int] , __lowercase : List[Image.Image] , __lowercase : int = 50 ) -> np.ndarray: assert isinstance(self.scheduler , __lowercase ) self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE__ : str =(sample / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : str =torch.Tensor(__lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE__ : Tuple =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE__ : Any =self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : int =( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : int =1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Optional[Any] =self.unet(__lowercase , __lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =(1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE__ : str =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE__ : Any =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __magic_name__ ( __lowercase : torch.Tensor , __lowercase : torch.Tensor , __lowercase : float ) -> torch.Tensor: SCREAMING_SNAKE_CASE__ : Optional[int] =acos(torch.dot(torch.flatten(__lowercase ) , torch.flatten(__lowercase ) ) / torch.norm(__lowercase ) / torch.norm(__lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowercase ) + sin(alpha * theta ) * xa / sin(__lowercase )
665
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """pegasus""" snake_case_ = ["""past_key_values"""] snake_case_ = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[Any] , __lowercase : List[Any]=5_02_65 , __lowercase : Union[str, Any]=10_24 , __lowercase : Optional[Any]=12 , __lowercase : List[str]=40_96 , __lowercase : int=16 , __lowercase : List[Any]=12 , __lowercase : Any=40_96 , __lowercase : List[str]=16 , __lowercase : Any=0.0 , __lowercase : Union[str, Any]=0.0 , __lowercase : str=True , __lowercase : Dict=True , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=10_24 , __lowercase : Optional[int]=0.1 , __lowercase : List[Any]=0.0 , __lowercase : Any=0.0 , __lowercase : Tuple=0.02 , __lowercase : Union[str, Any]=0 , __lowercase : Tuple=False , __lowercase : str=0 , __lowercase : Optional[int]=1 , __lowercase : List[Any]=1 , **__lowercase : Tuple , ) -> Dict: SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] =d_model SCREAMING_SNAKE_CASE__ : Tuple =encoder_ffn_dim SCREAMING_SNAKE_CASE__ : str =encoder_layers SCREAMING_SNAKE_CASE__ : List[str] =encoder_attention_heads SCREAMING_SNAKE_CASE__ : Any =decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[Any] =decoder_layers SCREAMING_SNAKE_CASE__ : Any =decoder_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] =dropout SCREAMING_SNAKE_CASE__ : Optional[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : Any =activation_dropout SCREAMING_SNAKE_CASE__ : List[Any] =activation_function SCREAMING_SNAKE_CASE__ : str =init_std SCREAMING_SNAKE_CASE__ : Optional[int] =encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[int] =decoder_layerdrop SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Union[str, Any] =encoder_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=__lowercase , eos_token_id=__lowercase , is_encoder_decoder=__lowercase , decoder_start_token_id=__lowercase , forced_eos_token_id=__lowercase , **__lowercase , ) @property def __magic_name__ ( self : List[Any] ) -> int: return self.encoder_attention_heads @property def __magic_name__ ( self : List[str] ) -> int: return self.d_model
665
'''simple docstring''' from math import isqrt def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Any =False return [i for i in range(2, UpperCamelCase__ ) if is_prime[i]] def _a( UpperCamelCase__ : int = 1_0**8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =calculate_prime_numbers(max_number // 2 ) SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _a( UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =[] for part_id in partition_order: SCREAMING_SNAKE_CASE__ : Tuple =df.where(f"SPARK_PARTITION_ID() = {part_id}" ).collect() for row_idx, row in enumerate(UpperCamelCase__ ): expected_row_ids_and_row_dicts.append((f"{part_id}_{row_idx}", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Optional[int] =spark.range(1_0_0 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : int =Spark(UpperCamelCase__ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=1_6 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 5_0 @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : str =spark.range(1_0 ).repartition(2 ) SCREAMING_SNAKE_CASE__ : Any =[1, 0] SCREAMING_SNAKE_CASE__ : int =_generate_iterable_examples(UpperCamelCase__, UpperCamelCase__ ) # Reverse the partitions. SCREAMING_SNAKE_CASE__ : Union[str, Any] =_get_expected_row_ids_and_row_dicts_for_partition_order(UpperCamelCase__, UpperCamelCase__ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Any =spark.range(1_0 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : Dict =SparkExamplesIterable(UpperCamelCase__ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(UpperCamelCase__ ): assert row_id == f"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : List[str] =spark.range(3_0 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: SCREAMING_SNAKE_CASE__ : List[str] =lambda UpperCamelCase__ : x.reverse() SCREAMING_SNAKE_CASE__ : List[Any] =_get_expected_row_ids_and_row_dicts_for_partition_order(UpperCamelCase__, [2, 1, 0] ) SCREAMING_SNAKE_CASE__ : List[Any] =SparkExamplesIterable(UpperCamelCase__ ).shuffle_data_sources(UpperCamelCase__ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : List[Any] =spark.range(2_0 ).repartition(4 ) # Partitions 0 and 2 SCREAMING_SNAKE_CASE__ : Optional[Any] =SparkExamplesIterable(UpperCamelCase__ ).shard_data_sources(worker_id=0, num_workers=2 ) assert shard_it_a.n_shards == 2 SCREAMING_SNAKE_CASE__ : Optional[Any] =_get_expected_row_ids_and_row_dicts_for_partition_order(UpperCamelCase__, [0, 2] ) for i, (row_id, row_dict) in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 SCREAMING_SNAKE_CASE__ : Dict =SparkExamplesIterable(UpperCamelCase__ ).shard_data_sources(worker_id=1, num_workers=2 ) assert shard_it_a.n_shards == 2 SCREAMING_SNAKE_CASE__ : int =_get_expected_row_ids_and_row_dicts_for_partition_order(UpperCamelCase__, [1, 3] ) for i, (row_id, row_dict) in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() SCREAMING_SNAKE_CASE__ : List[str] =spark.range(1_0_0 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : str =Spark(UpperCamelCase__ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_0_0
665
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = SpeechTaTokenizer snake_case_ = False snake_case_ = True def __magic_name__ ( self : int ) -> Any: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[Any] =SpeechTaTokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken('''<mask>''' , lstrip=__lowercase , rstrip=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Dict , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''this is a test''' SCREAMING_SNAKE_CASE__ : int ='''this is a test''' return input_text, output_text def __magic_name__ ( self : List[Any] , __lowercase : int , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=20 , __lowercase : Any=5 ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_input_output_texts(__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.decode(__lowercase , clean_up_tokenization_spaces=__lowercase ) return text, ids def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] ='''<pad>''' SCREAMING_SNAKE_CASE__ : Optional[int] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__lowercase ) , 81 ) def __magic_name__ ( self : Dict ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Any =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ : int =['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.add_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ : str ={'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} SCREAMING_SNAKE_CASE__ : int =tokenizer.add_special_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size_a + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __magic_name__ ( self : Optional[Any] ) -> Any: pass def __magic_name__ ( self : List[str] ) -> List[Any]: pass def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_ids(__lowercase ) # fmt: off self.assertListEqual(__lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.convert_ids_to_tokens(__lowercase ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __magic_name__ ( self : List[str] ) -> List[str]: # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE__ : List[Any] =[ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off SCREAMING_SNAKE_CASE__ : str ={ '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__lowercase , )
665
1
'''simple docstring''' from jiwer import compute_measures import datasets a_ = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' a_ = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' a_ = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def __magic_name__ ( self : List[str] ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def __magic_name__ ( self : Tuple , __lowercase : List[Any]=None , __lowercase : Optional[Any]=None , __lowercase : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(__lowercase , __lowercase )["wer"] else: SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : List[Any] =0 for prediction, reference in zip(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[int] =compute_measures(__lowercase , __lowercase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
665
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {'configuration_timm_backbone': ['TimmBackboneConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['TimmBackbone'] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } a_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = BertTokenizer def __init__( self : int , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : str=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Tuple="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : str=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : int =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Any =do_lower_case SCREAMING_SNAKE_CASE__ : Any =strip_accents SCREAMING_SNAKE_CASE__ : Dict =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Union[str, Any] =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =do_lower_case def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Union[str, Any]=None ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =[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 __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowercase : List[str] , __lowercase : Optional[Any]=13 , __lowercase : List[str]=7 , __lowercase : Dict=True , __lowercase : str=True , __lowercase : List[str]=False , __lowercase : Union[str, Any]=True , __lowercase : List[Any]=99 , __lowercase : Optional[int]=32 , __lowercase : Any=5 , __lowercase : List[Any]=4 , __lowercase : Optional[Any]=37 , __lowercase : Optional[Any]="gelu" , __lowercase : str=0.1 , __lowercase : List[str]=0.1 , __lowercase : Tuple=5_12 , __lowercase : Optional[Any]=16 , __lowercase : List[Any]=2 , __lowercase : List[Any]=0.02 , __lowercase : List[Any]=3 , __lowercase : Tuple=4 , __lowercase : List[Any]=None , ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : Dict =seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =is_training SCREAMING_SNAKE_CASE__ : Dict =use_input_mask SCREAMING_SNAKE_CASE__ : Tuple =use_token_type_ids SCREAMING_SNAKE_CASE__ : Optional[int] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =vocab_size SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : Any =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple =type_sequence_label_size SCREAMING_SNAKE_CASE__ : str =initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] =num_labels SCREAMING_SNAKE_CASE__ : int =num_choices SCREAMING_SNAKE_CASE__ : List[str] =scope def __magic_name__ ( self : Union[str, Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Tuple =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : int =None SCREAMING_SNAKE_CASE__ : Optional[Any] =None SCREAMING_SNAKE_CASE__ : Union[str, Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[str] =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : Tuple ) -> Tuple: return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Union[str, Any] , __lowercase : List[str] , __lowercase : str , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple , __lowercase : List[str] , __lowercase : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =LlamaModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , attention_mask=__lowercase ) SCREAMING_SNAKE_CASE__ : int =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Tuple , __lowercase : Tuple , __lowercase : List[str] , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : int , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , ) -> Dict: SCREAMING_SNAKE_CASE__ : int =True SCREAMING_SNAKE_CASE__ : int =LlamaModel(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase , attention_mask=__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[Any] , __lowercase : List[Any] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Any , __lowercase : str , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : List[str] , ) -> int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =LlamaForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Tuple , __lowercase : List[Any] , __lowercase : Optional[Any] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Any , __lowercase : int , __lowercase : Optional[Any] , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Any =LlamaForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ : Any =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , use_cache=__lowercase , ) SCREAMING_SNAKE_CASE__ : Optional[int] =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] =ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Tuple =torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int =torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , output_hidden_states=__lowercase , )['''hidden_states'''][0] SCREAMING_SNAKE_CASE__ : Any =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , past_key_values=__lowercase , output_hidden_states=__lowercase , )['''hidden_states'''][0] # select random slice SCREAMING_SNAKE_CASE__ : str =ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : str =output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Tuple =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowercase , __lowercase , atol=1e-3 ) ) def __magic_name__ ( self : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Union[str, Any] =config_and_inputs SCREAMING_SNAKE_CASE__ : Tuple ={'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () snake_case_ = (LlamaForCausalLM,) if is_torch_available() else () snake_case_ = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : str =LlamaModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : Dict ) -> str: self.config_tester.run_common_tests() def __magic_name__ ( self : List[str] ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : str =type self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =3 SCREAMING_SNAKE_CASE__ : Optional[Any] =input_dict['''input_ids'''] SCREAMING_SNAKE_CASE__ : Any =input_ids.ne(1 ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any =LlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : str =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __magic_name__ ( self : Union[str, Any] ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict =3 SCREAMING_SNAKE_CASE__ : List[str] ='''single_label_classification''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =input_dict['''input_ids'''] SCREAMING_SNAKE_CASE__ : Any =input_ids.ne(1 ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any =LlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =3 SCREAMING_SNAKE_CASE__ : Tuple ='''multi_label_classification''' SCREAMING_SNAKE_CASE__ : Dict =input_dict['''input_ids'''] SCREAMING_SNAKE_CASE__ : str =input_ids.ne(1 ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : List[str] =LlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' ) def __magic_name__ ( self : Any ) -> str: pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def __magic_name__ ( self : Tuple , __lowercase : Optional[int] ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int =ids_tensor([1, 10] , config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ : Tuple =LlamaModel(__lowercase ) original_model.to(__lowercase ) original_model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =original_model(__lowercase ).last_hidden_state SCREAMING_SNAKE_CASE__ : Any =original_model(__lowercase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ : Optional[Any] ={'''type''': scaling_type, '''factor''': 10.0} SCREAMING_SNAKE_CASE__ : Union[str, Any] =LlamaModel(__lowercase ) scaled_model.to(__lowercase ) scaled_model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =scaled_model(__lowercase ).last_hidden_state SCREAMING_SNAKE_CASE__ : Optional[Any] =scaled_model(__lowercase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : str =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] SCREAMING_SNAKE_CASE__ : Optional[Any] =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , __lowercase , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1e-5 , rtol=1e-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def __magic_name__ ( self : Optional[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : str =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] SCREAMING_SNAKE_CASE__ : List[Any] =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(torch.tensor(__lowercase ) ) # Expected mean on dim = -1 SCREAMING_SNAKE_CASE__ : int =torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , __lowercase , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1e-5 , rtol=1e-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def __magic_name__ ( self : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] SCREAMING_SNAKE_CASE__ : Optional[Any] =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''' ) SCREAMING_SNAKE_CASE__ : str =model(torch.tensor(__lowercase ) ) # Expected mean on dim = -1 SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , __lowercase , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off SCREAMING_SNAKE_CASE__ : str =torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , __lowercase , atol=1e-2 , rtol=1e-2 ) @unittest.skip( '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' ) @slow def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] SCREAMING_SNAKE_CASE__ : List[Any] =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''' ) SCREAMING_SNAKE_CASE__ : int =model(torch.tensor(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , __lowercase , atol=1e-2 , rtol=1e-2 ) # fmt: off SCREAMING_SNAKE_CASE__ : Dict =torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1e-5 , rtol=1e-5 ) @unittest.skip('''Model is curently gated''' ) @slow def __magic_name__ ( self : List[Any] ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] ='''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi''' SCREAMING_SNAKE_CASE__ : Dict ='''Simply put, the theory of relativity states that ''' SCREAMING_SNAKE_CASE__ : Optional[int] =LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' ) SCREAMING_SNAKE_CASE__ : Any =tokenizer.encode(__lowercase , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : Dict =LlamaForCausalLM.from_pretrained( '''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=__lowercase ) # greedy generation outputs SCREAMING_SNAKE_CASE__ : int =model.generate(__lowercase , max_new_tokens=64 , top_p=__lowercase , temperature=1 , do_sample=__lowercase ) SCREAMING_SNAKE_CASE__ : int =tokenizer.decode(generated_ids[0] , skip_special_tokens=__lowercase ) self.assertEqual(__lowercase , __lowercase )
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
'''simple docstring''' import itertools import string from collections.abc import Generator, Iterable def _a( UpperCamelCase__ : Iterable[str], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =iter(UpperCamelCase__ ) while True: SCREAMING_SNAKE_CASE__ : Dict =tuple(itertools.islice(UpperCamelCase__, UpperCamelCase__ ) ) if not chunk: return yield chunk def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =''''''.join([c.upper() for c in dirty if c in string.ascii_letters] ) SCREAMING_SNAKE_CASE__ : str ='''''' if len(UpperCamelCase__ ) < 2: return dirty for i in range(len(UpperCamelCase__ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(UpperCamelCase__ ) & 1: clean += "X" return clean def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''ABCDEFGHIKLMNOPQRSTUVWXYZ''' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler SCREAMING_SNAKE_CASE__ : Optional[Any] =[] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(UpperCamelCase__ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(UpperCamelCase__ ) return table def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =generate_table(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =prepare_input(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str ='''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCamelCase__, 2 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =divmod(table.index(UpperCamelCase__ ), 5 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =divmod(table.index(UpperCamelCase__ ), 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =generate_table(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int ='''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCamelCase__, 2 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =divmod(table.index(UpperCamelCase__ ), 5 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =divmod(table.index(UpperCamelCase__ ), 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case_ = 42 # Cache store of keys snake_case_ = 42 # References of the keys in cache snake_case_ = 10 # Maximum capacity of cache def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Any =deque() SCREAMING_SNAKE_CASE__ : str =set() if not n: SCREAMING_SNAKE_CASE__ : Optional[Any] =sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =n def __magic_name__ ( self : List[str] , __lowercase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE__ : int =self.dq_store.pop() self.key_reference.remove(__lowercase ) else: self.dq_store.remove(__lowercase ) self.dq_store.appendleft(__lowercase ) self.key_reference.add(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> None: for k in self.dq_store: print(__lowercase ) def __repr__( self : List[Any] ) -> str: return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() a_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
665
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Optional[int]=12 , __lowercase : Any=7 , __lowercase : int=True , __lowercase : Optional[int]=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=99 , __lowercase : int=32 , __lowercase : Dict=32 , __lowercase : int=2 , __lowercase : List[Any]=4 , __lowercase : Any=37 , __lowercase : Union[str, Any]=0.1 , __lowercase : str=0.1 , __lowercase : Dict=5_12 , __lowercase : Optional[Any]=0.02 , __lowercase : str=0 , __lowercase : Optional[int]=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : str =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : str =seq_length SCREAMING_SNAKE_CASE__ : str =is_training SCREAMING_SNAKE_CASE__ : int =use_input_mask SCREAMING_SNAKE_CASE__ : Tuple =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] =projection_dim SCREAMING_SNAKE_CASE__ : Optional[int] =num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] =num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] =intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] =dropout SCREAMING_SNAKE_CASE__ : List[str] =attention_dropout SCREAMING_SNAKE_CASE__ : Dict =max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE__ : Dict =scope SCREAMING_SNAKE_CASE__ : List[str] =bos_token_id def __magic_name__ ( self : int ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : str =random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: SCREAMING_SNAKE_CASE__ : List[Any] =input_mask.numpy() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =input_mask.shape SCREAMING_SNAKE_CASE__ : List[Any] =np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =1 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 SCREAMING_SNAKE_CASE__ : str =self.get_config() return config, input_ids, tf.convert_to_tensor(__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def __magic_name__ ( self : int , __lowercase : Any , __lowercase : Dict , __lowercase : List[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =TFBlipTextModel(config=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , training=__lowercase ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase , training=__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ ( self : Any ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = (TFBlipTextModel,) if is_tf_available() else () snake_case_ = False snake_case_ = False snake_case_ = False def __magic_name__ ( self : Tuple ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] =BlipTextModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : List[str] ) -> Union[str, Any]: self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Dict: pass def __magic_name__ ( self : Tuple ) -> List[str]: pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def __magic_name__ ( self : Any ) -> Optional[int]: pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def __magic_name__ ( self : List[str] ) -> List[Any]: pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def __magic_name__ ( self : Union[str, Any] ) -> int: pass @slow def __magic_name__ ( self : str ) -> str: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] =TFBlipTextModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : int , __lowercase : List[Any]=True ) -> Any: super().test_pt_tf_model_equivalence(allow_missing_keys=__lowercase )
665
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' 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 a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'spiece.model'} a_ = { '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' ), } } a_ = { 'google/bigbird-roberta-base': 4_0_9_6, 'google/bigbird-roberta-large': 4_0_9_6, 'google/bigbird-base-trivia-itc': 4_0_9_6, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): 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 : Any , __lowercase : Union[str, Any] , __lowercase : Tuple="<unk>" , __lowercase : Optional[Any]="<s>" , __lowercase : List[str]="</s>" , __lowercase : Dict="<pad>" , __lowercase : Dict="[SEP]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Dict="[CLS]" , __lowercase : Optional[Dict[str, Any]] = None , **__lowercase : str , ) -> None: SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else bos_token SCREAMING_SNAKE_CASE__ : List[str] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else eos_token SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else unk_token SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else pad_token SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else cls_token SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : str =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token SCREAMING_SNAKE_CASE__ : List[str] ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , pad_token=__lowercase , sep_token=__lowercase , mask_token=__lowercase , cls_token=__lowercase , sp_model_kwargs=self.sp_model_kwargs , **__lowercase , ) SCREAMING_SNAKE_CASE__ : Dict =vocab_file SCREAMING_SNAKE_CASE__ : Tuple =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowercase ) @property def __magic_name__ ( self : Union[str, Any] ) -> List[str]: return self.sp_model.get_piece_size() def __magic_name__ ( self : Dict ) -> Dict: SCREAMING_SNAKE_CASE__ : Tuple ={self.convert_ids_to_tokens(__lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple =self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Dict =None return state def __setstate__( self : str , __lowercase : Any ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE__ : Optional[int] ={} SCREAMING_SNAKE_CASE__ : List[Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __magic_name__ ( self : Optional[int] , __lowercase : str ) -> List[str]: return self.sp_model.encode(__lowercase , out_type=__lowercase ) def __magic_name__ ( self : int , __lowercase : Any ) -> List[str]: return self.sp_model.piece_to_id(__lowercase ) def __magic_name__ ( self : Dict , __lowercase : int ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =self.sp_model.IdToPiece(__lowercase ) return token def __magic_name__ ( self : List[str] , __lowercase : Optional[int] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Tuple =[] SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''''' SCREAMING_SNAKE_CASE__ : Optional[int] =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(__lowercase ) + token SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : Tuple =[] else: current_sub_tokens.append(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =False out_string += self.sp_model.decode(__lowercase ) return out_string.strip() def __magic_name__ ( self : List[str] , __lowercase : List[int] , __lowercase : bool = False , __lowercase : bool = None , __lowercase : bool = True , **__lowercase : Tuple , ) -> str: SCREAMING_SNAKE_CASE__ : Dict =kwargs.pop('''use_source_tokenizer''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.convert_ids_to_tokens(__lowercase , skip_special_tokens=__lowercase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE__ : List[str] =[] SCREAMING_SNAKE_CASE__ : List[Any] =[] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__lowercase ) ) SCREAMING_SNAKE_CASE__ : str =[] sub_texts.append(__lowercase ) else: current_sub_text.append(__lowercase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__lowercase ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: SCREAMING_SNAKE_CASE__ : str =re.sub(r''' (\[(MASK|SEP)\])''' , r'''\1''' , ''' '''.join(__lowercase ) ) else: SCREAMING_SNAKE_CASE__ : List[str] =''''''.join(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE__ : int =self.clean_up_tokenization(__lowercase ) return clean_text else: return text def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowercase ) elif not os.path.isfile(self.vocab_file ): with open(__lowercase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE__ : Optional[int] =self.sp_model.serialized_model_proto() fi.write(__lowercase ) return (out_vocab_file,) def __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] =[self.cls_token_id] SCREAMING_SNAKE_CASE__ : int =[self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def __magic_name__ ( self : Any , __lowercase : List[int] , __lowercase : Optional[List[int]] = None , __lowercase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1] + ([0] * len(__lowercase )) + [1] def __magic_name__ ( self : Optional[int] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : str =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
665
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
1
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker a_ = 'CompVis/stable-diffusion-v1-1' a_ = 'CompVis/stable-diffusion-v1-2' a_ = 'CompVis/stable-diffusion-v1-3' a_ = 'CompVis/stable-diffusion-v1-4' class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Tuple , __lowercase : AutoencoderKL , __lowercase : CLIPTextModel , __lowercase : CLIPTokenizer , __lowercase : UNetaDConditionModel , __lowercase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __lowercase : StableDiffusionSafetyChecker , __lowercase : CLIPImageProcessor , __lowercase : bool = True , ) -> List[str]: super()._init_() SCREAMING_SNAKE_CASE__ : str =StableDiffusionPipeline.from_pretrained(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =StableDiffusionPipeline.from_pretrained(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =StableDiffusionPipeline.from_pretrained(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =StableDiffusionPipeline( vae=__lowercase , text_encoder=__lowercase , tokenizer=__lowercase , unet=__lowercase , scheduler=__lowercase , safety_checker=__lowercase , feature_extractor=__lowercase , requires_safety_checker=__lowercase , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def __magic_name__ ( self : Optional[Any] ) -> Dict[str, Any]: return {k: getattr(self , __lowercase ) for k in self.config.keys() if not k.startswith('''_''' )} def __magic_name__ ( self : List[Any] , __lowercase : Optional[Union[str, int]] = "auto" ) -> Any: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE__ : str =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> int: self.enable_attention_slicing(__lowercase ) @torch.no_grad() def __magic_name__ ( self : Optional[Any] , __lowercase : Union[str, List[str]] , __lowercase : int = 5_12 , __lowercase : int = 5_12 , __lowercase : int = 50 , __lowercase : float = 7.5 , __lowercase : Optional[Union[str, List[str]]] = None , __lowercase : Optional[int] = 1 , __lowercase : float = 0.0 , __lowercase : Optional[torch.Generator] = None , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[str] = "pil" , __lowercase : bool = True , __lowercase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowercase : int = 1 , **__lowercase : Optional[Any] , ) -> Optional[int]: return self.pipea( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) @torch.no_grad() def __magic_name__ ( self : Any , __lowercase : Union[str, List[str]] , __lowercase : int = 5_12 , __lowercase : int = 5_12 , __lowercase : int = 50 , __lowercase : float = 7.5 , __lowercase : Optional[Union[str, List[str]]] = None , __lowercase : Optional[int] = 1 , __lowercase : float = 0.0 , __lowercase : Optional[torch.Generator] = None , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[str] = "pil" , __lowercase : bool = True , __lowercase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowercase : int = 1 , **__lowercase : List[str] , ) -> List[str]: return self.pipea( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) @torch.no_grad() def __magic_name__ ( self : Dict , __lowercase : Union[str, List[str]] , __lowercase : int = 5_12 , __lowercase : int = 5_12 , __lowercase : int = 50 , __lowercase : float = 7.5 , __lowercase : Optional[Union[str, List[str]]] = None , __lowercase : Optional[int] = 1 , __lowercase : float = 0.0 , __lowercase : Optional[torch.Generator] = None , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[str] = "pil" , __lowercase : bool = True , __lowercase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowercase : int = 1 , **__lowercase : Any , ) -> List[Any]: return self.pipea( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) @torch.no_grad() def __magic_name__ ( self : Optional[Any] , __lowercase : Union[str, List[str]] , __lowercase : int = 5_12 , __lowercase : int = 5_12 , __lowercase : int = 50 , __lowercase : float = 7.5 , __lowercase : Optional[Union[str, List[str]]] = None , __lowercase : Optional[int] = 1 , __lowercase : float = 0.0 , __lowercase : Optional[torch.Generator] = None , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[str] = "pil" , __lowercase : bool = True , __lowercase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowercase : int = 1 , **__lowercase : Optional[Any] , ) -> Tuple: return self.pipea( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) @torch.no_grad() def __magic_name__ ( self : int , __lowercase : Union[str, List[str]] , __lowercase : int = 5_12 , __lowercase : int = 5_12 , __lowercase : int = 50 , __lowercase : float = 7.5 , __lowercase : Optional[Union[str, List[str]]] = None , __lowercase : Optional[int] = 1 , __lowercase : float = 0.0 , __lowercase : Optional[torch.Generator] = None , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[str] = "pil" , __lowercase : bool = True , __lowercase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowercase : int = 1 , **__lowercase : Optional[int] , ) -> Dict: SCREAMING_SNAKE_CASE__ : Tuple ='''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__lowercase ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 SCREAMING_SNAKE_CASE__ : Any =self.textaimg_sda_a( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) # Get first result from Stable Diffusion Checkpoint v1.2 SCREAMING_SNAKE_CASE__ : Optional[Any] =self.textaimg_sda_a( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) # Get first result from Stable Diffusion Checkpoint v1.3 SCREAMING_SNAKE_CASE__ : Optional[int] =self.textaimg_sda_a( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) # Get first result from Stable Diffusion Checkpoint v1.4 SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.textaimg_sda_a( prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1
'''simple docstring''' import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : float , __lowercase : int ) -> Any: if k in (0.04, 0.06): SCREAMING_SNAKE_CASE__ : Dict =k SCREAMING_SNAKE_CASE__ : List[str] =window_size else: raise ValueError('''invalid k value''' ) def __str__( self : Tuple ) -> str: return str(self.k ) def __magic_name__ ( self : List[str] , __lowercase : str ) -> tuple[cva.Mat, list[list[int]]]: SCREAMING_SNAKE_CASE__ : str =cva.imread(__lowercase , 0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =img.shape SCREAMING_SNAKE_CASE__ : list[list[int]] =[] SCREAMING_SNAKE_CASE__ : int =img.copy() SCREAMING_SNAKE_CASE__ : Optional[int] =cva.cvtColor(__lowercase , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =np.gradient(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =dx**2 SCREAMING_SNAKE_CASE__ : List[str] =dy**2 SCREAMING_SNAKE_CASE__ : Optional[Any] =dx * dy SCREAMING_SNAKE_CASE__ : Optional[int] =0.04 SCREAMING_SNAKE_CASE__ : Tuple =self.window_size // 2 for y in range(__lowercase , h - offset ): for x in range(__lowercase , w - offset ): SCREAMING_SNAKE_CASE__ : Dict =ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE__ : Dict =iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE__ : Union[str, Any] =ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE__ : Optional[Any] =(wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE__ : Optional[Any] =wxx + wyy SCREAMING_SNAKE_CASE__ : Optional[int] =det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": a_ = HarrisCorner(0.04, 3) a_ , a_ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
665
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': {'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'}, 'tokenizer_file': { 'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json' }, } a_ = {'mobilebert-uncased': 5_1_2} a_ = {} class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = MobileBertTokenizer def __init__( self : int , __lowercase : int=None , __lowercase : str=None , __lowercase : int=True , __lowercase : List[str]="[UNK]" , __lowercase : Union[str, Any]="[SEP]" , __lowercase : Optional[Any]="[PAD]" , __lowercase : Tuple="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : int=True , __lowercase : Tuple=None , **__lowercase : Union[str, Any] , ) -> Dict: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : Optional[int] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : str =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : List[Any] =do_lower_case SCREAMING_SNAKE_CASE__ : List[str] =strip_accents SCREAMING_SNAKE_CASE__ : Optional[int] =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Any =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =do_lower_case def __magic_name__ ( self : Tuple , __lowercase : Optional[int] , __lowercase : Tuple=None ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __magic_name__ ( self : List[Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[Any] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : Union[str, Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : str =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[str]] =[[] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Tuple =key - 1 if key <= 0: raise ValueError('''Height of grid can\'t be 0 or negative''' ) if key == 1 or len(UpperCamelCase__ ) <= key: return input_string for position, character in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =position % (lowest * 2) # puts it in bounds SCREAMING_SNAKE_CASE__ : Optional[Any] =min(UpperCamelCase__, lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =[''''''.join(UpperCamelCase__ ) for row in temp_grid] SCREAMING_SNAKE_CASE__ : Tuple =''''''.join(UpperCamelCase__ ) return output_string def _a( UpperCamelCase__ : str, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[] SCREAMING_SNAKE_CASE__ : Any =key - 1 if key <= 0: raise ValueError('''Height of grid can\'t be 0 or negative''' ) if key == 1: return input_string SCREAMING_SNAKE_CASE__ : list[list[str]] =[[] for _ in range(UpperCamelCase__ )] # generates template for position in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : str =position % (lowest * 2) # puts it in bounds SCREAMING_SNAKE_CASE__ : int =min(UpperCamelCase__, lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append('''*''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for row in temp_grid: # fills in the characters SCREAMING_SNAKE_CASE__ : List[str] =input_string[counter : counter + len(UpperCamelCase__ )] grid.append(list(UpperCamelCase__ ) ) counter += len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] ='''''' # reads as zigzag for position in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : Tuple =position % (lowest * 2) # puts it in bounds SCREAMING_SNAKE_CASE__ : Any =min(UpperCamelCase__, lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple ={} for key_guess in range(1, len(UpperCamelCase__ ) ): # tries every key SCREAMING_SNAKE_CASE__ : Optional[int] =decrypt(UpperCamelCase__, UpperCamelCase__ ) return results if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
1
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask a_ = logging.getLogger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Union[str, Any] , __lowercase : Dict=-1 ) -> Any: # in NER datasets, the last column is usually reserved for NER label SCREAMING_SNAKE_CASE__ : Dict =label_idx def __magic_name__ ( self : List[str] , __lowercase : Optional[int] , __lowercase : Union[Split, str] ) -> List[InputExample]: if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Dict =mode.value SCREAMING_SNAKE_CASE__ : List[Any] =os.path.join(__lowercase , F"{mode}.txt" ) SCREAMING_SNAKE_CASE__ : List[Any] =1 SCREAMING_SNAKE_CASE__ : Optional[int] =[] with open(__lowercase , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE__ : Tuple =[] SCREAMING_SNAKE_CASE__ : int =[] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__lowercase , labels=__lowercase ) ) guid_index += 1 SCREAMING_SNAKE_CASE__ : str =[] SCREAMING_SNAKE_CASE__ : List[Any] =[] else: SCREAMING_SNAKE_CASE__ : Tuple =line.split(''' ''' ) words.append(splits[0] ) if len(__lowercase ) > 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=__lowercase , labels=__lowercase ) ) return examples def __magic_name__ ( self : Dict , __lowercase : TextIO , __lowercase : TextIO , __lowercase : List ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Tuple =0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(__lowercase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: SCREAMING_SNAKE_CASE__ : List[Any] =line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(__lowercase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def __magic_name__ ( self : Tuple , __lowercase : str ) -> List[str]: if path: with open(__lowercase , '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] =f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE__ : Dict =['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : int ) -> Dict: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __magic_name__ ( self : Optional[int] , __lowercase : str ) -> List[str]: if path: with open(__lowercase , '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] =f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE__ : Dict =['''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 __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __magic_name__ ( self : Optional[Any] , __lowercase : Optional[int] , __lowercase : Union[Split, str] ) -> List[InputExample]: if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : str =mode.value SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join(__lowercase , F"{mode}.txt" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =1 SCREAMING_SNAKE_CASE__ : List[Any] =[] with open(__lowercase , encoding='''utf-8''' ) as f: for sentence in parse_incr(__lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =[] SCREAMING_SNAKE_CASE__ : int =[] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(__lowercase ) == len(__lowercase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__lowercase , labels=__lowercase ) ) guid_index += 1 return examples def __magic_name__ ( self : Tuple , __lowercase : TextIO , __lowercase : TextIO , __lowercase : List ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =0 for sentence in parse_incr(__lowercase ): SCREAMING_SNAKE_CASE__ : Optional[int] =preds_list[example_id] SCREAMING_SNAKE_CASE__ : int ='''''' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__lowercase ) example_id += 1 def __magic_name__ ( self : int , __lowercase : str ) -> List[str]: if path: with open(__lowercase , '''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", ]
665
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _a( UpperCamelCase__ : str, UpperCamelCase__ : Tuple, UpperCamelCase__ : Any, UpperCamelCase__ : List[str], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase__ ) as metadata_file: SCREAMING_SNAKE_CASE__ : Optional[int] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =LukeConfig(use_entity_aware_attention=UpperCamelCase__, **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(UpperCamelCase__, map_location='''cpu''' )['''module'''] # Load the entity vocab file SCREAMING_SNAKE_CASE__ : List[str] =load_original_entity_vocab(UpperCamelCase__ ) # add an entry for [MASK2] SCREAMING_SNAKE_CASE__ : Optional[int] =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 SCREAMING_SNAKE_CASE__ : Optional[int] =XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken('''<ent>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =AddedToken('''<ent2>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int ='''MLukeTokenizer''' with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE__ : str =tokenizer.convert_tokens_to_ids(['''@'''] )[0] SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.convert_tokens_to_ids(['''#'''] )[0] SCREAMING_SNAKE_CASE__ : Dict =state_dict['''embeddings.word_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : List[str] =word_emb[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Tuple =word_emb[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[bias_name] SCREAMING_SNAKE_CASE__ : List[Any] =decoder_bias[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =decoder_bias[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE__ : Tuple =f"encoder.layer.{layer_index}.attention.self." SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : List[Any] =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE__ : Any =state_dict['''entity_embeddings.entity_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : Any =entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict['''entity_predictions.bias'''] SCREAMING_SNAKE_CASE__ : Tuple =entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_prediction_bias, entity_mask_bias] ) SCREAMING_SNAKE_CASE__ : int =LukeForMaskedLM(config=UpperCamelCase__ ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) SCREAMING_SNAKE_CASE__ : Tuple =OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[key] else: SCREAMING_SNAKE_CASE__ : Any =state_dict[key] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if set(UpperCamelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(f"Unexpected unexpected_keys: {unexpected_keys}" ) if set(UpperCamelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs SCREAMING_SNAKE_CASE__ : Any =MLukeTokenizer.from_pretrained(UpperCamelCase__, task='''entity_classification''' ) SCREAMING_SNAKE_CASE__ : str ='''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =(0, 9) SCREAMING_SNAKE_CASE__ : str =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =model(**UpperCamelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : str =torch.Size((1, 3_3, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : Any =torch.Size((1, 1, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" f" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify masked word/entity prediction SCREAMING_SNAKE_CASE__ : str =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''Tokyo is the capital of <mask>.''' SCREAMING_SNAKE_CASE__ : Dict =(2_4, 3_0) SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[str] =model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =encoding['''input_ids'''][0].tolist() SCREAMING_SNAKE_CASE__ : Any =input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.entity_logits[0][0].argmax().item() SCREAMING_SNAKE_CASE__ : Dict =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(UpperCamelCase__ ) ) model.save_pretrained(UpperCamelCase__ ) def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =['''[MASK]''', '''[PAD]''', '''[UNK]'''] SCREAMING_SNAKE_CASE__ : List[str] =[json.loads(UpperCamelCase__ ) for line in open(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Optional[int] ={} for entry in data: SCREAMING_SNAKE_CASE__ : Tuple =entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: SCREAMING_SNAKE_CASE__ : str =entity_id break SCREAMING_SNAKE_CASE__ : Union[str, Any] =f"{language}:{entity_name}" SCREAMING_SNAKE_CASE__ : Union[str, Any] =entity_id return new_mapping if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a_ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
665
1
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""image_processor""", """tokenizer"""] snake_case_ = """ViltImageProcessor""" snake_case_ = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : Optional[int] , __lowercase : List[str]=None , __lowercase : Dict=None , **__lowercase : List[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __lowercase , ) SCREAMING_SNAKE_CASE__ : List[str] =kwargs.pop('''feature_extractor''' ) SCREAMING_SNAKE_CASE__ : str =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =self.image_processor def __call__( self : Any , __lowercase : List[str] , __lowercase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __lowercase : bool = True , __lowercase : Union[bool, str, PaddingStrategy] = False , __lowercase : Union[bool, str, TruncationStrategy] = None , __lowercase : Optional[int] = None , __lowercase : int = 0 , __lowercase : Optional[int] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = True , __lowercase : Optional[Union[str, TensorType]] = None , **__lowercase : Optional[Any] , ) -> BatchEncoding: SCREAMING_SNAKE_CASE__ : Tuple =self.tokenizer( text=__lowercase , add_special_tokens=__lowercase , padding=__lowercase , truncation=__lowercase , max_length=__lowercase , stride=__lowercase , pad_to_multiple_of=__lowercase , return_token_type_ids=__lowercase , return_attention_mask=__lowercase , return_overflowing_tokens=__lowercase , return_special_tokens_mask=__lowercase , return_offsets_mapping=__lowercase , return_length=__lowercase , verbose=__lowercase , return_tensors=__lowercase , **__lowercase , ) # add pixel_values + pixel_mask SCREAMING_SNAKE_CASE__ : Optional[int] =self.image_processor(__lowercase , return_tensors=__lowercase ) encoding.update(__lowercase ) return encoding def __magic_name__ ( self : Any , *__lowercase : Any , **__lowercase : Optional[int] ) -> List[str]: return self.tokenizer.batch_decode(*__lowercase , **__lowercase ) def __magic_name__ ( self : Any , *__lowercase : Tuple , **__lowercase : List[str] ) -> Union[str, Any]: return self.tokenizer.decode(*__lowercase , **__lowercase ) @property def __magic_name__ ( self : List[str] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Dict =self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : List[str] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __magic_name__ ( self : str ) -> Tuple: warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __lowercase , ) return self.image_processor_class @property def __magic_name__ ( self : Optional[int] ) -> int: warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __lowercase , ) return self.image_processor
665
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : List[Any] =True for i in range(UpperCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE__ : Optional[int] =True if a[i].islower(): SCREAMING_SNAKE_CASE__ : List[Any] =True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ = { 'configuration_conditional_detr': [ 'CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConditionalDetrConfig', 'ConditionalDetrOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['ConditionalDetrFeatureExtractor'] a_ = ['ConditionalDetrImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConditionalDetrForObjectDetection', 'ConditionalDetrForSegmentation', 'ConditionalDetrModel', 'ConditionalDetrPreTrainedModel', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[Any] , __lowercase : List[str]=13 , __lowercase : int=7 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : List[Any]=True , __lowercase : str=True , __lowercase : Tuple=99 , __lowercase : Union[str, Any]=64 , __lowercase : Tuple=32 , __lowercase : Optional[Any]=5 , __lowercase : Tuple=4 , __lowercase : Optional[int]=37 , __lowercase : int="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : List[Any]=0.1 , __lowercase : List[Any]=5_12 , __lowercase : int=16 , __lowercase : Optional[int]=2 , __lowercase : Tuple=0.02 , __lowercase : List[str]=3 , __lowercase : List[str]=4 , __lowercase : List[str]=None , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =seq_length SCREAMING_SNAKE_CASE__ : Dict =is_training SCREAMING_SNAKE_CASE__ : List[Any] =use_input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] =use_labels SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : str =hidden_size SCREAMING_SNAKE_CASE__ : Any =embedding_size SCREAMING_SNAKE_CASE__ : Tuple =num_hidden_layers SCREAMING_SNAKE_CASE__ : str =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : Any =type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE__ : str =num_labels SCREAMING_SNAKE_CASE__ : List[str] =num_choices SCREAMING_SNAKE_CASE__ : List[str] =scope def __magic_name__ ( self : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : int =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =None SCREAMING_SNAKE_CASE__ : Optional[Any] =None SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : List[str] ) -> Any: return MegatronBertConfig( 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 , embedding_size=self.embedding_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=__lowercase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Any , __lowercase : Tuple , __lowercase : Any , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ ( self : Dict , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : Any , __lowercase : Optional[int] , __lowercase : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =MegatronBertForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : List[str] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : str , __lowercase : Any , __lowercase : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =MegatronBertForNextSentencePrediction(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : List[str] , __lowercase : Optional[int] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForPreTraining(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , next_sentence_label=__lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any , __lowercase : Any , __lowercase : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =MegatronBertForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __magic_name__ ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : int , __lowercase : List[str] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.num_labels SCREAMING_SNAKE_CASE__ : Dict =MegatronBertForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple =self.num_labels SCREAMING_SNAKE_CASE__ : int =MegatronBertForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : Dict , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Any , __lowercase : List[Any] , __lowercase : int , __lowercase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.num_choices SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[int] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : str ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True # test_resize_embeddings = False snake_case_ = False def __magic_name__ ( self : List[Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : Tuple=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str ) -> Dict: self.config_tester.run_common_tests() def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowercase ) def __magic_name__ ( self : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowercase ) def __magic_name__ ( self : Dict ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowercase ) def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' return torch.tensor( UpperCamelCase__, dtype=torch.long, device=UpperCamelCase__, ) a_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow @unittest.skip('''Model is not available.''' ) def __magic_name__ ( self : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any ='''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ : Optional[int] =os.path.join(os.environ['''MYDIR'''] , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =MegatronBertModel.from_pretrained(__lowercase ) model.to(__lowercase ) model.half() SCREAMING_SNAKE_CASE__ : Dict =_long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase )[0] SCREAMING_SNAKE_CASE__ : Dict =torch.Size((1, 9, 10_24) ) self.assertEqual(output.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : str =[-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ : List[Any] =output[0, ii, jj] SCREAMING_SNAKE_CASE__ : Tuple =expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ : List[str] ='''ii={} jj={} a={} b={}'''.format(__lowercase , __lowercase , __lowercase , __lowercase ) self.assertTrue(math.isclose(__lowercase , __lowercase , rel_tol=__lowercase , abs_tol=__lowercase ) , msg=__lowercase )
665
1
'''simple docstring''' import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Dict =self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(__lowercase , '''neck_hidden_sizes''' ) ) self.parent.assertTrue(hasattr(__lowercase , '''num_attention_heads''' ) ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , __lowercase : List[Any] , __lowercase : Optional[Any]=13 , __lowercase : Any=32 , __lowercase : Union[str, Any]=2 , __lowercase : Any=3 , __lowercase : Tuple=6_40 , __lowercase : Optional[Any]=4 , __lowercase : Optional[int]="silu" , __lowercase : List[str]=3 , __lowercase : int=32 , __lowercase : Tuple=0.1 , __lowercase : List[Any]=0.1 , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[Any]=0.02 , __lowercase : int=True , __lowercase : Optional[Any]=True , __lowercase : Optional[int]=10 , __lowercase : Optional[Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : str =parent SCREAMING_SNAKE_CASE__ : List[Any] =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_channels SCREAMING_SNAKE_CASE__ : Tuple =last_hidden_size SCREAMING_SNAKE_CASE__ : Tuple =num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] =hidden_act SCREAMING_SNAKE_CASE__ : Tuple =conv_kernel_size SCREAMING_SNAKE_CASE__ : Any =output_stride SCREAMING_SNAKE_CASE__ : str =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =classifier_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =num_labels SCREAMING_SNAKE_CASE__ : Tuple =initializer_range SCREAMING_SNAKE_CASE__ : Dict =scope def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any =None SCREAMING_SNAKE_CASE__ : Any =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[str] =self.get_config() return config, pixel_values, labels, pixel_labels def __magic_name__ ( self : int ) -> List[Any]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Optional[Any] , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : Union[str, Any] , __lowercase : Optional[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Dict =MobileViTModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __magic_name__ ( self : Any , __lowercase : str , __lowercase : Optional[Any] , __lowercase : List[Any] , __lowercase : str ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.num_labels SCREAMING_SNAKE_CASE__ : Tuple =MobileViTForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Dict , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : str ) -> Any: SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels SCREAMING_SNAKE_CASE__ : Optional[int] =MobileViTForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : List[str] =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": MobileViTModel, """image-classification""": MobileViTForImageClassification, """image-segmentation""": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def __magic_name__ ( self : Tuple ) -> Dict: SCREAMING_SNAKE_CASE__ : Tuple =MobileViTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] =MobileViTConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def __magic_name__ ( self : Any ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViT does not use inputs_embeds''' ) def __magic_name__ ( self : Union[str, Any] ) -> Any: pass @unittest.skip(reason='''MobileViT does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[int]: pass @unittest.skip(reason='''MobileViT does not output attentions''' ) def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: pass def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __magic_name__ ( self : List[str] ) -> int: pass def __magic_name__ ( self : Dict ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> List[Any]: def check_hidden_states_output(__lowercase : Optional[Any] , __lowercase : str , __lowercase : str ): SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Any =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Dict =5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. SCREAMING_SNAKE_CASE__ : Tuple =2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def __magic_name__ ( self : Any ) -> str: SCREAMING_SNAKE_CASE__ : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Dict =MobileViTModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : int ) -> Union[str, Any]: return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small''' ) if is_vision_available() else None @slow def __magic_name__ ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small''' ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.default_image_processor SCREAMING_SNAKE_CASE__ : int =prepare_img() SCREAMING_SNAKE_CASE__ : List[Any] =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor([-1.9364, -1.2327, -0.4653] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) ) @slow def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple =MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model.to(__lowercase ) SCREAMING_SNAKE_CASE__ : int =MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) SCREAMING_SNAKE_CASE__ : int =prepare_img() SCREAMING_SNAKE_CASE__ : Optional[Any] =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Any =torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1e-4 ) ) @slow def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : List[Any] =MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =prepare_img() SCREAMING_SNAKE_CASE__ : Any =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : int =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ : Any =image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =image_processor.post_process_semantic_segmentation(outputs=__lowercase ) SCREAMING_SNAKE_CASE__ : int =torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
665
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() SCREAMING_SNAKE_CASE__ : List[str] =[sys.executable] + distributed_args execute_subprocess_async(__lowercase , env=os.environ.copy() )
665
1
'''simple docstring''' import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = FunnelTokenizer snake_case_ = FunnelTokenizerFast snake_case_ = True snake_case_ = True def __magic_name__ ( self : int ) -> Union[str, Any]: super().setUp() SCREAMING_SNAKE_CASE__ : List[str] =[ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE__ : Any =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __magic_name__ ( self : Optional[int] , **__lowercase : Optional[int] ) -> str: return FunnelTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def __magic_name__ ( self : str , **__lowercase : Dict ) -> Tuple: return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **__lowercase ) def __magic_name__ ( self : Dict , __lowercase : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE__ : List[Any] ='''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE__ : Dict ='''unwanted, running''' return input_text, output_text def __magic_name__ ( self : Union[str, Any] ) -> Any: SCREAMING_SNAKE_CASE__ : str =self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__lowercase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase ) , [7, 4, 5, 10, 8, 9] ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Tuple =tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = ShapEImgaImgPipeline snake_case_ = ["""image"""] snake_case_ = ["""image"""] snake_case_ = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[Any] ) -> List[Any]: return 32 @property def __magic_name__ ( self : List[str] ) -> Optional[int]: return 32 @property def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: return self.time_input_dim * 4 @property def __magic_name__ ( self : Dict ) -> Union[str, Any]: return 8 @property def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) SCREAMING_SNAKE_CASE__ : str =CLIPVisionModel(__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =CLIPImageProcessor( crop_size=2_24 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __magic_name__ ( self : List[str] ) -> Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str ={ '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } SCREAMING_SNAKE_CASE__ : str =PriorTransformer(**__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE__ : str =ShapERenderer(**__lowercase ) return model def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.dummy_prior SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_encoder SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_processor SCREAMING_SNAKE_CASE__ : Tuple =self.dummy_renderer SCREAMING_SNAKE_CASE__ : int =HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=__lowercase , clip_sample=__lowercase , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ : Any ={ '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __magic_name__ ( self : Any , __lowercase : List[str] , __lowercase : Any=0 ) -> Any: SCREAMING_SNAKE_CASE__ : int =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : List[str] =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : List[str] ) -> str: SCREAMING_SNAKE_CASE__ : int ='''cpu''' SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : str =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] =np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __magic_name__ ( self : List[Any] ) -> List[str]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch_device == '''cpu''' SCREAMING_SNAKE_CASE__ : Optional[Any] =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowercase , relax_max_difference=__lowercase , ) def __magic_name__ ( self : Dict ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =1 SCREAMING_SNAKE_CASE__ : List[str] =2 SCREAMING_SNAKE_CASE__ : Dict =self.get_dummy_inputs(__lowercase ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ : Tuple =batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ : List[Any] =pipe(**__lowercase , num_images_per_prompt=__lowercase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Optional[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) SCREAMING_SNAKE_CASE__ : Dict =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) SCREAMING_SNAKE_CASE__ : List[Any] =ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) SCREAMING_SNAKE_CASE__ : Tuple =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple =pipe( __lowercase , generator=__lowercase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) SCREAMING_SNAKE_CASE__ : Tuple =str(bin(UpperCamelCase__ ) ) binary_number += "0" * shift_amount return binary_number def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) SCREAMING_SNAKE_CASE__ : str =str(bin(UpperCamelCase__ ) )[2:] if shift_amount >= len(UpperCamelCase__ ): return "0b0" SCREAMING_SNAKE_CASE__ : List[str] =binary_number[: len(UpperCamelCase__ ) - shift_amount] return "0b" + shifted_binary_number def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' if number >= 0: # Get binary representation of positive number SCREAMING_SNAKE_CASE__ : int ='''0''' + str(bin(UpperCamelCase__ ) ).strip('''-''' )[2:] else: # Get binary (2's complement) representation of negative number SCREAMING_SNAKE_CASE__ : List[str] =len(bin(UpperCamelCase__ )[3:] ) # Find 2's complement of number SCREAMING_SNAKE_CASE__ : List[Any] =bin(abs(UpperCamelCase__ ) - (1 << binary_number_length) )[3:] SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''1''' + '''0''' * (binary_number_length - len(UpperCamelCase__ )) + binary_number ) if shift_amount >= len(UpperCamelCase__ ): return "0b" + binary_number[0] * len(UpperCamelCase__ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(UpperCamelCase__ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_bigcode""" snake_case_ = ["""past_key_values"""] snake_case_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Any , __lowercase : Any=5_02_57 , __lowercase : int=10_24 , __lowercase : List[str]=7_68 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : List[str]=None , __lowercase : int="gelu_pytorch_tanh" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=1e-5 , __lowercase : List[str]=0.02 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=5_02_56 , __lowercase : List[Any]=5_02_56 , __lowercase : Union[str, Any]=True , __lowercase : List[str]=True , __lowercase : Dict=True , **__lowercase : List[Any] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_positions SCREAMING_SNAKE_CASE__ : Dict =n_embd SCREAMING_SNAKE_CASE__ : Dict =n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_head SCREAMING_SNAKE_CASE__ : List[str] =n_inner SCREAMING_SNAKE_CASE__ : List[str] =activation_function SCREAMING_SNAKE_CASE__ : List[Any] =resid_pdrop SCREAMING_SNAKE_CASE__ : List[Any] =embd_pdrop SCREAMING_SNAKE_CASE__ : List[str] =attn_pdrop SCREAMING_SNAKE_CASE__ : Dict =layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =scale_attn_weights SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Dict =attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : int =scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Dict =multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] =eos_token_id super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase )
665
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'facebook/data2vec-vision-base-ft': ( 'https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """data2vec-vision""" def __init__( self : Tuple , __lowercase : str=7_68 , __lowercase : Tuple=12 , __lowercase : Tuple=12 , __lowercase : Optional[int]=30_72 , __lowercase : Any="gelu" , __lowercase : List[Any]=0.0 , __lowercase : Dict=0.0 , __lowercase : str=0.02 , __lowercase : List[str]=1e-12 , __lowercase : Tuple=2_24 , __lowercase : Dict=16 , __lowercase : int=3 , __lowercase : Dict=False , __lowercase : Optional[Any]=False , __lowercase : List[str]=False , __lowercase : Optional[Any]=False , __lowercase : Tuple=0.1 , __lowercase : int=0.1 , __lowercase : List[Any]=True , __lowercase : List[Any]=[3, 5, 7, 11] , __lowercase : Any=[1, 2, 3, 6] , __lowercase : Dict=True , __lowercase : Optional[int]=0.4 , __lowercase : Optional[Any]=2_56 , __lowercase : Tuple=1 , __lowercase : Optional[Any]=False , __lowercase : int=2_55 , **__lowercase : Any , ) -> List[str]: super().__init__(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] =num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] =num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Any =hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] =initializer_range SCREAMING_SNAKE_CASE__ : int =layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict =image_size SCREAMING_SNAKE_CASE__ : List[Any] =patch_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : List[Any] =use_mask_token SCREAMING_SNAKE_CASE__ : List[str] =use_absolute_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_relative_position_bias SCREAMING_SNAKE_CASE__ : List[Any] =use_shared_relative_position_bias SCREAMING_SNAKE_CASE__ : str =layer_scale_init_value SCREAMING_SNAKE_CASE__ : Optional[int] =drop_path_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_mean_pooling # decode head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ : Dict =out_indices SCREAMING_SNAKE_CASE__ : int =pool_scales # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_auxiliary_head SCREAMING_SNAKE_CASE__ : str =auxiliary_loss_weight SCREAMING_SNAKE_CASE__ : Optional[int] =auxiliary_channels SCREAMING_SNAKE_CASE__ : Any =auxiliary_num_convs SCREAMING_SNAKE_CASE__ : List[Any] =auxiliary_concat_input SCREAMING_SNAKE_CASE__ : List[str] =semantic_loss_ignore_index class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = version.parse("""1.11""" ) @property def __magic_name__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __magic_name__ ( self : List[str] ) -> float: return 1e-4
665
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =size SCREAMING_SNAKE_CASE__ : List[Any] =[0] * size SCREAMING_SNAKE_CASE__ : str =[0] * size @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return index | (index + 1) @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return (index & (index + 1)) - 1 def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =value while index < self.size: SCREAMING_SNAKE_CASE__ : Any =self.get_prev(__lowercase ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : List[str] =value else: SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_next(__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> int: right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : str =0 while left <= right: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_prev(__lowercase ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[Any] =max(__lowercase , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Any =current_left else: SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """git_vision_model""" def __init__( self : int , __lowercase : List[Any]=7_68 , __lowercase : List[str]=30_72 , __lowercase : List[Any]=12 , __lowercase : Tuple=12 , __lowercase : Tuple=3 , __lowercase : Optional[int]=2_24 , __lowercase : Optional[int]=16 , __lowercase : Tuple="quick_gelu" , __lowercase : List[str]=1e-5 , __lowercase : Dict=0.0 , __lowercase : List[str]=0.02 , **__lowercase : List[Any] , ) -> Tuple: super().__init__(**__lowercase ) SCREAMING_SNAKE_CASE__ : int =hidden_size SCREAMING_SNAKE_CASE__ : List[Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Tuple =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] =num_channels SCREAMING_SNAKE_CASE__ : Optional[int] =patch_size SCREAMING_SNAKE_CASE__ : Optional[int] =image_size SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : Any =attention_dropout SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_act @classmethod def __magic_name__ ( cls : Union[str, Any] , __lowercase : Union[str, os.PathLike] , **__lowercase : List[str] ) -> "PretrainedConfig": cls._set_token_in_kwargs(__lowercase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =cls.get_config_dict(__lowercase , **__lowercase ) # get the vision config dict if we are loading from GITConfig if config_dict.get('''model_type''' ) == "git": SCREAMING_SNAKE_CASE__ : Optional[Any] =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(__lowercase , **__lowercase ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """git""" def __init__( self : List[str] , __lowercase : List[Any]=None , __lowercase : Any=3_05_22 , __lowercase : Union[str, Any]=7_68 , __lowercase : List[str]=6 , __lowercase : Tuple=12 , __lowercase : int=30_72 , __lowercase : List[Any]="gelu" , __lowercase : int=0.1 , __lowercase : Tuple=0.1 , __lowercase : List[str]=10_24 , __lowercase : List[Any]=0.02 , __lowercase : Optional[int]=1e-12 , __lowercase : Dict=0 , __lowercase : Dict="absolute" , __lowercase : Dict=True , __lowercase : Dict=False , __lowercase : int=1_01 , __lowercase : List[Any]=1_02 , __lowercase : Any=None , **__lowercase : List[Any] , ) -> str: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , pad_token_id=__lowercase , **__lowercase ) if vision_config is None: SCREAMING_SNAKE_CASE__ : str ={} logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''' ) SCREAMING_SNAKE_CASE__ : Dict =GitVisionConfig(**__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_size SCREAMING_SNAKE_CASE__ : List[Any] =num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict =num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict =max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : int =position_embedding_type SCREAMING_SNAKE_CASE__ : List[str] =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : List[Any] =num_image_with_embedding SCREAMING_SNAKE_CASE__ : Dict =bos_token_id SCREAMING_SNAKE_CASE__ : Dict =eos_token_id def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ : Any =self.__class__.model_type return output
665
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""vqvae"""] def __init__( self : int , __lowercase : AutoencoderKL , __lowercase : UNetaDConditionModel , __lowercase : Mel , __lowercase : Union[DDIMScheduler, DDPMScheduler] , ) -> int: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase , mel=__lowercase , vqvae=__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return 50 if isinstance(self.scheduler , __lowercase ) else 10_00 @torch.no_grad() def __call__( self : Dict , __lowercase : int = 1 , __lowercase : str = None , __lowercase : np.ndarray = None , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = None , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : float = 0 , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : torch.Tensor = None , __lowercase : torch.Tensor = None , __lowercase : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: SCREAMING_SNAKE_CASE__ : Optional[Any] =steps or self.get_default_steps() self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE__ : Optional[int] =randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowercase , device=self.device , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =noise SCREAMING_SNAKE_CASE__ : List[str] =None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.mel.audio_slice_to_image(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE__ : int =(input_image / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =self.vqvae.encode(torch.unsqueeze(__lowercase , 0 ) ).latent_dist.sample( generator=__lowercase )[0] SCREAMING_SNAKE_CASE__ : int =self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE__ : Optional[Any] =int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : Tuple =int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowercase ): SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase , __lowercase )['''sample'''] else: SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase )['''sample'''] if isinstance(self.scheduler , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , eta=__lowercase , generator=__lowercase , )['''prev_sample'''] else: SCREAMING_SNAKE_CASE__ : Any =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , generator=__lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE__ : List[str] =mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE__ : str =1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE__ : int =self.vqvae.decode(__lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE__ : Dict =(images * 2_55).round().astype('''uint8''' ) SCREAMING_SNAKE_CASE__ : Any =list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[self.mel.image_to_audio(__lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowercase ) ) @torch.no_grad() def __magic_name__ ( self : Optional[int] , __lowercase : List[Image.Image] , __lowercase : int = 50 ) -> np.ndarray: assert isinstance(self.scheduler , __lowercase ) self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE__ : str =(sample / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : str =torch.Tensor(__lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE__ : Tuple =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE__ : Any =self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : int =( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : int =1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Optional[Any] =self.unet(__lowercase , __lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =(1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE__ : str =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE__ : Any =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __magic_name__ ( __lowercase : torch.Tensor , __lowercase : torch.Tensor , __lowercase : float ) -> torch.Tensor: SCREAMING_SNAKE_CASE__ : Optional[int] =acos(torch.dot(torch.flatten(__lowercase ) , torch.flatten(__lowercase ) ) / torch.norm(__lowercase ) / torch.norm(__lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowercase ) + sin(alpha * theta ) * xa / sin(__lowercase )
665
1
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Tuple , __lowercase : Optional[Any] , __lowercase : Dict=7 , __lowercase : List[str]=3 , __lowercase : str=30 , __lowercase : int=4_00 , __lowercase : Optional[int]=True , __lowercase : Tuple=None , __lowercase : List[Any]=True , __lowercase : Dict=[0.5, 0.5, 0.5] , __lowercase : Optional[Any]=[0.5, 0.5, 0.5] , __lowercase : Optional[int]=True , __lowercase : List[str]=1 / 2_55 , __lowercase : int=True , ) -> Dict: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE__ : int =size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 13_33} SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[Any] =batch_size SCREAMING_SNAKE_CASE__ : List[str] =num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] =min_resolution SCREAMING_SNAKE_CASE__ : Optional[Any] =max_resolution SCREAMING_SNAKE_CASE__ : List[str] =do_resize SCREAMING_SNAKE_CASE__ : Tuple =size SCREAMING_SNAKE_CASE__ : Any =do_normalize SCREAMING_SNAKE_CASE__ : int =image_mean SCREAMING_SNAKE_CASE__ : str =image_std SCREAMING_SNAKE_CASE__ : List[Any] =do_rescale SCREAMING_SNAKE_CASE__ : List[str] =rescale_factor SCREAMING_SNAKE_CASE__ : List[str] =do_pad def __magic_name__ ( self : Optional[int] ) -> Tuple: 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 __magic_name__ ( self : Optional[int] , __lowercase : str , __lowercase : Union[str, Any]=False ) -> List[str]: if not batched: SCREAMING_SNAKE_CASE__ : Optional[Any] =image_inputs[0] if isinstance(__lowercase , Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =image.size else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE__ : Optional[int] =int(self.size['''shortest_edge'''] * h / w ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.size['''shortest_edge'''] elif w > h: SCREAMING_SNAKE_CASE__ : List[Any] =self.size['''shortest_edge'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =int(self.size['''shortest_edge'''] * w / h ) else: SCREAMING_SNAKE_CASE__ : List[Any] =self.size['''shortest_edge'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.size['''shortest_edge'''] else: SCREAMING_SNAKE_CASE__ : Optional[int] =[] for image in image_inputs: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) SCREAMING_SNAKE_CASE__ : Any =max(__lowercase , key=lambda __lowercase : item[0] )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , key=lambda __lowercase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = ConditionalDetrImageProcessor if is_vision_available() else None def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =ConditionalDetrImageProcessingTester(self ) @property def __magic_name__ ( self : Optional[int] ) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __magic_name__ ( self : Any ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , '''image_mean''' ) ) self.assertTrue(hasattr(__lowercase , '''image_std''' ) ) self.assertTrue(hasattr(__lowercase , '''do_normalize''' ) ) self.assertTrue(hasattr(__lowercase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowercase , '''size''' ) ) def __magic_name__ ( self : Optional[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 13_33} ) self.assertEqual(image_processor.do_pad , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__lowercase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , __lowercase ) def __magic_name__ ( self : Optional[int] ) -> List[Any]: pass def __magic_name__ ( self : Any ) -> Any: # Initialize image_processing SCREAMING_SNAKE_CASE__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =self.image_processor_tester.get_expected_values(__lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.image_processor_tester.get_expected_values(__lowercase , batched=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __magic_name__ ( self : str ) -> Optional[Any]: # Initialize image_processing SCREAMING_SNAKE_CASE__ : Tuple =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : Dict =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , numpify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =self.image_processor_tester.get_expected_values(__lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ : str =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.image_processor_tester.get_expected_values(__lowercase , batched=__lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __magic_name__ ( self : Optional[int] ) -> List[str]: # Initialize image_processing SCREAMING_SNAKE_CASE__ : str =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , torchify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : str =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.image_processor_tester.get_expected_values(__lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ : Dict =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.image_processor_tester.get_expected_values(__lowercase , batched=__lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __magic_name__ ( self : Union[str, Any] ) -> Any: # prepare image and target SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[int] =json.loads(f.read() ) SCREAMING_SNAKE_CASE__ : int ={'''image_id''': 3_97_69, '''annotations''': target} # encode them SCREAMING_SNAKE_CASE__ : Optional[int] =ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50''' ) SCREAMING_SNAKE_CASE__ : Dict =image_processing(images=__lowercase , annotations=__lowercase , return_tensors='''pt''' ) # verify pixel values SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['''pixel_values'''].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __lowercase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE__ : Dict =torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __lowercase ) ) # verify boxes SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __lowercase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE__ : int =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __lowercase ) ) # verify is_crowd SCREAMING_SNAKE_CASE__ : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __lowercase ) ) # verify class_labels SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __lowercase ) ) # verify orig_size SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __lowercase ) ) # verify size SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __lowercase ) ) @slow def __magic_name__ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: SCREAMING_SNAKE_CASE__ : int =json.loads(f.read() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''file_name''': '''000000039769.png''', '''image_id''': 3_97_69, '''segments_info''': target} SCREAMING_SNAKE_CASE__ : Any =pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them SCREAMING_SNAKE_CASE__ : Optional[int] =ConditionalDetrImageProcessor(format='''coco_panoptic''' ) SCREAMING_SNAKE_CASE__ : str =image_processing(images=__lowercase , annotations=__lowercase , masks_path=__lowercase , return_tensors='''pt''' ) # verify pixel values SCREAMING_SNAKE_CASE__ : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['''pixel_values'''].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __lowercase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __lowercase ) ) # verify boxes SCREAMING_SNAKE_CASE__ : str =torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __lowercase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE__ : int =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __lowercase ) ) # verify is_crowd SCREAMING_SNAKE_CASE__ : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __lowercase ) ) # verify class_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __lowercase ) ) # verify masks SCREAMING_SNAKE_CASE__ : Tuple =82_28_73 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , __lowercase ) # verify orig_size SCREAMING_SNAKE_CASE__ : List[str] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __lowercase ) ) # verify size SCREAMING_SNAKE_CASE__ : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __lowercase ) )
665
'''simple docstring''' from math import isqrt def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Any =False return [i for i in range(2, UpperCamelCase__ ) if is_prime[i]] def _a( UpperCamelCase__ : int = 1_0**8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =calculate_prime_numbers(max_number // 2 ) SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: a_ = None a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json' ), }, } a_ = { 'facebook/nllb-large-en-ro': 1_0_2_4, 'facebook/nllb-200-distilled-600M': 1_0_2_4, } # fmt: off a_ = ['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn'] class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = ["""input_ids""", """attention_mask"""] snake_case_ = NllbTokenizer snake_case_ = [] snake_case_ = [] def __init__( self : Any , __lowercase : int=None , __lowercase : str=None , __lowercase : str="<s>" , __lowercase : Any="</s>" , __lowercase : List[str]="</s>" , __lowercase : Any="<s>" , __lowercase : Optional[int]="<unk>" , __lowercase : List[Any]="<pad>" , __lowercase : Any="<mask>" , __lowercase : Any=None , __lowercase : str=None , __lowercase : Union[str, Any]=None , __lowercase : str=False , **__lowercase : List[str] , ) -> Optional[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token SCREAMING_SNAKE_CASE__ : Union[str, Any] =legacy_behaviour super().__init__( vocab_file=__lowercase , tokenizer_file=__lowercase , bos_token=__lowercase , eos_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , unk_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , src_lang=__lowercase , tgt_lang=__lowercase , additional_special_tokens=__lowercase , legacy_behaviour=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : List[str] =vocab_file SCREAMING_SNAKE_CASE__ : str =False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ : Union[str, Any] =FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : List[Any] ={ lang_code: self.convert_tokens_to_ids(__lowercase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE__ : Optional[int] =src_lang if src_lang is not None else '''eng_Latn''' SCREAMING_SNAKE_CASE__ : Dict =self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE__ : List[str] =tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __magic_name__ ( self : Optional[int] ) -> str: return self._src_lang @src_lang.setter def __magic_name__ ( self : List[Any] , __lowercase : str ) -> None: SCREAMING_SNAKE_CASE__ : List[Any] =new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __magic_name__ ( self : Optional[int] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __magic_name__ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __magic_name__ ( self : Any , __lowercase : str , __lowercase : str , __lowercase : Optional[str] , __lowercase : Optional[str] , **__lowercase : Dict ) -> List[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =src_lang SCREAMING_SNAKE_CASE__ : Any =self(__lowercase , add_special_tokens=__lowercase , return_tensors=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : int =self.convert_tokens_to_ids(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =tgt_lang_id return inputs def __magic_name__ ( self : int , __lowercase : List[str] , __lowercase : str = "eng_Latn" , __lowercase : Optional[List[str]] = None , __lowercase : str = "fra_Latn" , **__lowercase : Optional[Any] , ) -> BatchEncoding: SCREAMING_SNAKE_CASE__ : Union[str, Any] =src_lang SCREAMING_SNAKE_CASE__ : str =tgt_lang return super().prepare_seqaseq_batch(__lowercase , __lowercase , **__lowercase ) def __magic_name__ ( self : int ) -> Any: return self.set_src_lang_special_tokens(self.src_lang ) def __magic_name__ ( self : List[str] ) -> Union[str, Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __magic_name__ ( self : str , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =self.convert_tokens_to_ids(__lowercase ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : List[Any] =[] SCREAMING_SNAKE_CASE__ : Optional[int] =[self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Tuple =[self.eos_token_id] SCREAMING_SNAKE_CASE__ : Tuple =self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : List[Any] =self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Dict =processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __magic_name__ ( self : Optional[Any] , __lowercase : str ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =self.convert_tokens_to_ids(__lowercase ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : Any =[] SCREAMING_SNAKE_CASE__ : Optional[int] =[self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =[self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.eos_token_id] SCREAMING_SNAKE_CASE__ : List[Any] =self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Dict =self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Optional[int] =processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __magic_name__ ( self : Dict , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory." ) return SCREAMING_SNAKE_CASE__ : Tuple =os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
665
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = SpeechTaTokenizer snake_case_ = False snake_case_ = True def __magic_name__ ( self : int ) -> Any: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[Any] =SpeechTaTokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken('''<mask>''' , lstrip=__lowercase , rstrip=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Dict , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''this is a test''' SCREAMING_SNAKE_CASE__ : int ='''this is a test''' return input_text, output_text def __magic_name__ ( self : List[Any] , __lowercase : int , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=20 , __lowercase : Any=5 ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_input_output_texts(__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.decode(__lowercase , clean_up_tokenization_spaces=__lowercase ) return text, ids def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] ='''<pad>''' SCREAMING_SNAKE_CASE__ : Optional[int] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__lowercase ) , 81 ) def __magic_name__ ( self : Dict ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Any =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ : int =['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.add_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ : str ={'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} SCREAMING_SNAKE_CASE__ : int =tokenizer.add_special_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size_a + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __magic_name__ ( self : Optional[Any] ) -> Any: pass def __magic_name__ ( self : List[str] ) -> List[Any]: pass def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_ids(__lowercase ) # fmt: off self.assertListEqual(__lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.convert_ids_to_tokens(__lowercase ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __magic_name__ ( self : List[str] ) -> List[str]: # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE__ : List[Any] =[ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off SCREAMING_SNAKE_CASE__ : str ={ '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__lowercase , )
665
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a_ = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig', ], 'processing_altclip': ['AltCLIPProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'AltCLIPPreTrainedModel', 'AltCLIPModel', 'AltCLIPTextModel', 'AltCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
1
'''simple docstring''' from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline a_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __magic_name__ ( self : List[Any] , __lowercase : int ) -> str: if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Tuple =[label.strip() for label in labels.split(''',''' ) if label.strip()] return labels def __call__( self : Dict , __lowercase : Optional[int] , __lowercase : str , __lowercase : Optional[Any] ) -> Any: if len(__lowercase ) == 0 or len(__lowercase ) == 0: raise ValueError('''You must include at least one label and at least one sequence.''' ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. ''' '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.''' ).format(__lowercase ) ) if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : List[Any] =[sequences] SCREAMING_SNAKE_CASE__ : Any =[] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(__lowercase )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(lowerCamelCase ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Optional[Any] , __lowercase : Tuple=ZeroShotClassificationArgumentHandler() , *__lowercase : Optional[Any] , **__lowercase : Any ) -> int: SCREAMING_SNAKE_CASE__ : Dict =args_parser super().__init__(*__lowercase , **__lowercase ) if self.entailment_id == -1: logger.warning( '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to ''' '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.''' ) @property def __magic_name__ ( self : str ) -> Union[str, Any]: for label, ind in self.model.config.labelaid.items(): if label.lower().startswith('''entail''' ): return ind return -1 def __magic_name__ ( self : int , __lowercase : Dict , __lowercase : Dict=True , __lowercase : List[str]=True , __lowercase : Optional[int]=TruncationStrategy.ONLY_FIRST , **__lowercase : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int =self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use ''' ''' `pad_token=eos_token`''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.tokenizer.eos_token try: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.tokenizer( __lowercase , add_special_tokens=__lowercase , return_tensors=__lowercase , padding=__lowercase , truncation=__lowercase , ) except Exception as e: if "too short" in str(__lowercase ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. SCREAMING_SNAKE_CASE__ : Any =self.tokenizer( __lowercase , add_special_tokens=__lowercase , return_tensors=__lowercase , padding=__lowercase , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def __magic_name__ ( self : List[Any] , **__lowercase : List[str] ) -> Optional[Any]: if kwargs.get('''multi_class''' , __lowercase ) is not None: SCREAMING_SNAKE_CASE__ : Any =kwargs['''multi_class'''] logger.warning( '''The `multi_class` argument has been deprecated and renamed to `multi_label`. ''' '''`multi_class` will be removed in a future version of Transformers.''' ) SCREAMING_SNAKE_CASE__ : Any ={} if "candidate_labels" in kwargs: SCREAMING_SNAKE_CASE__ : Optional[Any] =self._args_parser._parse_labels(kwargs['''candidate_labels'''] ) if "hypothesis_template" in kwargs: SCREAMING_SNAKE_CASE__ : str =kwargs['''hypothesis_template'''] SCREAMING_SNAKE_CASE__ : Tuple ={} if "multi_label" in kwargs: SCREAMING_SNAKE_CASE__ : Any =kwargs['''multi_label'''] return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __lowercase : Union[str, List[str]] , *__lowercase : List[Any] , **__lowercase : List[Any] , ) -> Tuple: if len(__lowercase ) == 0: pass elif len(__lowercase ) == 1 and "candidate_labels" not in kwargs: SCREAMING_SNAKE_CASE__ : Dict =args[0] else: raise ValueError(F"Unable to understand extra arguments {args}" ) return super().__call__(__lowercase , **__lowercase ) def __magic_name__ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : Any=None , __lowercase : Any="This example is {}." ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =self._args_parser(__lowercase , __lowercase , __lowercase ) for i, (candidate_label, sequence_pair) in enumerate(zip(__lowercase , __lowercase ) ): SCREAMING_SNAKE_CASE__ : str =self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(__lowercase ) - 1, **model_input, } def __magic_name__ ( self : Tuple , __lowercase : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =inputs['''candidate_label'''] SCREAMING_SNAKE_CASE__ : str =inputs['''sequence'''] SCREAMING_SNAKE_CASE__ : List[Any] ={k: inputs[k] for k in self.tokenizer.model_input_names} SCREAMING_SNAKE_CASE__ : Any =self.model(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] ={ '''candidate_label''': candidate_label, '''sequence''': sequence, '''is_last''': inputs['''is_last'''], **outputs, } return model_outputs def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : Union[str, Any]=False ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =[outputs['''candidate_label'''] for outputs in model_outputs] SCREAMING_SNAKE_CASE__ : List[str] =[outputs['''sequence'''] for outputs in model_outputs] SCREAMING_SNAKE_CASE__ : Dict =np.concatenate([output['''logits'''].numpy() for output in model_outputs] ) SCREAMING_SNAKE_CASE__ : List[str] =logits.shape[0] SCREAMING_SNAKE_CASE__ : Tuple =len(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =N // n SCREAMING_SNAKE_CASE__ : Dict =logits.reshape((num_sequences, n, -1) ) if multi_label or len(__lowercase ) == 1: # softmax over the entailment vs. contradiction dim for each label independently SCREAMING_SNAKE_CASE__ : Optional[Any] =self.entailment_id SCREAMING_SNAKE_CASE__ : Optional[int] =-1 if entailment_id == 0 else 0 SCREAMING_SNAKE_CASE__ : Any =reshaped_outputs[..., [contradiction_id, entailment_id]] SCREAMING_SNAKE_CASE__ : Any =np.exp(__lowercase ) / np.exp(__lowercase ).sum(-1 , keepdims=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =scores[..., 1] else: # softmax the "entailment" logits over all candidate labels SCREAMING_SNAKE_CASE__ : int =reshaped_outputs[..., self.entailment_id] SCREAMING_SNAKE_CASE__ : List[Any] =np.exp(__lowercase ) / np.exp(__lowercase ).sum(-1 , keepdims=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } a_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = BertTokenizer def __init__( self : int , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : str=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Tuple="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : str=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : int =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Any =do_lower_case SCREAMING_SNAKE_CASE__ : Any =strip_accents SCREAMING_SNAKE_CASE__ : Dict =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Union[str, Any] =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =do_lower_case def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Union[str, Any]=None ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =[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 __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'microsoft/markuplm-base': 'https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json', 'microsoft/markuplm-large': 'https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """markuplm""" def __init__( self : Any , __lowercase : int=3_05_22 , __lowercase : Optional[Any]=7_68 , __lowercase : str=12 , __lowercase : Optional[Any]=12 , __lowercase : str=30_72 , __lowercase : Dict="gelu" , __lowercase : List[str]=0.1 , __lowercase : Any=0.1 , __lowercase : int=5_12 , __lowercase : Tuple=2 , __lowercase : Tuple=0.02 , __lowercase : Dict=1e-12 , __lowercase : str=0 , __lowercase : str=0 , __lowercase : List[Any]=2 , __lowercase : Optional[int]=2_56 , __lowercase : List[Any]=10_24 , __lowercase : str=2_16 , __lowercase : Any=10_01 , __lowercase : Optional[int]=32 , __lowercase : Any=50 , __lowercase : Union[str, Any]="absolute" , __lowercase : Any=True , __lowercase : List[str]=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =vocab_size SCREAMING_SNAKE_CASE__ : Dict =hidden_size SCREAMING_SNAKE_CASE__ : Any =num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int =max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] =type_vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : List[str] =layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple =position_embedding_type SCREAMING_SNAKE_CASE__ : Optional[Any] =use_cache SCREAMING_SNAKE_CASE__ : Optional[int] =classifier_dropout # additional properties SCREAMING_SNAKE_CASE__ : Tuple =max_depth SCREAMING_SNAKE_CASE__ : Any =max_xpath_tag_unit_embeddings SCREAMING_SNAKE_CASE__ : List[Any] =max_xpath_subs_unit_embeddings SCREAMING_SNAKE_CASE__ : Any =tag_pad_id SCREAMING_SNAKE_CASE__ : List[Any] =subs_pad_id SCREAMING_SNAKE_CASE__ : Tuple =xpath_unit_hidden_size
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def _a( UpperCamelCase__ : int, UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =int(UpperCamelCase__ ) assert noofclusters < len(UpperCamelCase__ ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : List[str] =len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : Optional[Any] =list(range(len(UpperCamelCase__ ) ) ) shuffle(UpperCamelCase__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : Any =tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : int =tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : Dict =[ tf.Variable(vectors[vector_indices[i]] ) for i in range(UpperCamelCase__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : str =tf.placeholder('''float64''', [dim] ) SCREAMING_SNAKE_CASE__ : Any =[] for centroid in centroids: cent_assigns.append(tf.assign(UpperCamelCase__, UpperCamelCase__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : Tuple =[tf.Variable(0 ) for i in range(len(UpperCamelCase__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : List[str] =tf.placeholder('''int32''' ) SCREAMING_SNAKE_CASE__ : List[str] =[] for assignment in assignments: cluster_assigns.append(tf.assign(UpperCamelCase__, UpperCamelCase__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : str =tf.placeholder('''float''', [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : List[str] =tf.reduce_mean(UpperCamelCase__, 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : Any =tf.placeholder('''float''', [dim] ) SCREAMING_SNAKE_CASE__ : List[str] =tf.placeholder('''float''', [dim] ) SCREAMING_SNAKE_CASE__ : Any =tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(UpperCamelCase__, UpperCamelCase__ ), 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : Optional[Any] =tf.placeholder('''float''', [noofclusters] ) SCREAMING_SNAKE_CASE__ : str =tf.argmin(UpperCamelCase__, 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : List[str] =tf.initialize_all_variables() # Initialize all variables sess.run(UpperCamelCase__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Dict =1_0_0 for _ in range(UpperCamelCase__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : Tuple =vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : Union[str, Any] =[ sess.run(UpperCamelCase__, feed_dict={va: vect, va: sess.run(UpperCamelCase__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : int =sess.run( UpperCamelCase__, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(UpperCamelCase__ ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : List[Any] =[ vectors[i] for i in range(len(UpperCamelCase__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : int =sess.run( UpperCamelCase__, feed_dict={mean_input: array(UpperCamelCase__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : Tuple =sess.run(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =sess.run(UpperCamelCase__ ) return centroids, assignments
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _a( UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =[ '''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(UpperCamelCase__, UpperCamelCase__ ) def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =emb.weight.shape SCREAMING_SNAKE_CASE__ : int =nn.Linear(UpperCamelCase__, UpperCamelCase__, bias=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =emb.weight.data return lin_layer def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =torch.load(UpperCamelCase__, map_location='''cpu''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =mam_aaa['''args'''] or mam_aaa['''cfg''']['''model'''] SCREAMING_SNAKE_CASE__ : int =mam_aaa['''model'''] remove_ignore_keys_(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =state_dict['''encoder.embed_tokens.weight'''].shape[0] SCREAMING_SNAKE_CASE__ : List[str] =MaMaaaConfig( vocab_size=UpperCamelCase__, max_position_embeddings=1_0_2_4, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, encoder_attention_heads=args.encoder_attention_heads, decoder_attention_heads=args.decoder_attention_heads, encoder_ffn_dim=args.encoder_ffn_embed_dim, decoder_ffn_dim=args.decoder_ffn_embed_dim, d_model=args.encoder_embed_dim, encoder_layerdrop=args.encoder_layerdrop, decoder_layerdrop=args.decoder_layerdrop, dropout=args.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_function='''relu''', ) SCREAMING_SNAKE_CASE__ : Tuple =state_dict['''decoder.embed_tokens.weight'''] SCREAMING_SNAKE_CASE__ : str =MaMaaaForConditionalGeneration(UpperCamelCase__ ) model.model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ = parser.parse_args() a_ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
665
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case_ = 42 # Cache store of keys snake_case_ = 42 # References of the keys in cache snake_case_ = 10 # Maximum capacity of cache def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Any =deque() SCREAMING_SNAKE_CASE__ : str =set() if not n: SCREAMING_SNAKE_CASE__ : Optional[Any] =sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =n def __magic_name__ ( self : List[str] , __lowercase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE__ : int =self.dq_store.pop() self.key_reference.remove(__lowercase ) else: self.dq_store.remove(__lowercase ) self.dq_store.appendleft(__lowercase ) self.key_reference.add(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> None: for k in self.dq_store: print(__lowercase ) def __repr__( self : List[Any] ) -> str: return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() a_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
665
1
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =size SCREAMING_SNAKE_CASE__ : List[Any] =[0] * size SCREAMING_SNAKE_CASE__ : str =[0] * size @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return index | (index + 1) @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return (index & (index + 1)) - 1 def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =value while index < self.size: SCREAMING_SNAKE_CASE__ : Any =self.get_prev(__lowercase ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : List[str] =value else: SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_next(__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> int: right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : str =0 while left <= right: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_prev(__lowercase ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[Any] =max(__lowercase , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Any =current_left else: SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def _a( UpperCamelCase__ : int ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) SCREAMING_SNAKE_CASE__ : Any =precision SCREAMING_SNAKE_CASE__ : Union[str, Any] =ceil(precision / 1_4 ) SCREAMING_SNAKE_CASE__ : Optional[int] =4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() SCREAMING_SNAKE_CASE__ : str =1 SCREAMING_SNAKE_CASE__ : int =1_3_5_9_1_4_0_9 SCREAMING_SNAKE_CASE__ : Any =Decimal(UpperCamelCase__ ) for k in range(1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =factorial(6 * k ) // (factorial(3 * k ) * factorial(UpperCamelCase__ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a_ = 5_0 print(F'''The first {n} digits of pi is: {pi(n)}''')
665
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
1
'''simple docstring''' from __future__ import annotations from typing import TypedDict class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = 42 snake_case_ = 42 def _a( UpperCamelCase__ : str ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''The parameter s type must be str.''' ) return [s[i:] + s[:i] for i in range(len(UpperCamelCase__ ) )] def _a( UpperCamelCase__ : str ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''The parameter s type must be str.''' ) if not s: raise ValueError('''The parameter s must not be empty.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =all_rotations(UpperCamelCase__ ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation SCREAMING_SNAKE_CASE__ : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(UpperCamelCase__ ), } return response def _a( UpperCamelCase__ : str, UpperCamelCase__ : int ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''The parameter bwt_string type must be str.''' ) if not bwt_string: raise ValueError('''The parameter bwt_string must not be empty.''' ) try: SCREAMING_SNAKE_CASE__ : Union[str, Any] =int(UpperCamelCase__ ) except ValueError: raise TypeError( '''The parameter idx_original_string type must be int or passive''' ''' of cast to int.''' ) if idx_original_string < 0: raise ValueError('''The parameter idx_original_string must not be lower than 0.''' ) if idx_original_string >= len(UpperCamelCase__ ): raise ValueError( '''The parameter idx_original_string must be lower than''' ''' len(bwt_string).''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =[''''''] * len(UpperCamelCase__ ) for _ in range(len(UpperCamelCase__ ) ): for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : List[Any] =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": a_ = 'Provide a string that I will generate its BWT transform: ' a_ = input(entry_msg).strip() a_ = bwt_transform(s) print( F'''Burrows Wheeler transform for string \'{s}\' results ''' F'''in \'{result['bwt_string']}\'''' ) a_ = reverse_bwt(result['bwt_string'], result['idx_original_string']) print( F'''Reversing Burrows Wheeler transform for entry \'{result['bwt_string']}\' ''' F'''we get original string \'{original_string}\'''' )
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1
'''simple docstring''' import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def _a( UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if "model" in orig_key: SCREAMING_SNAKE_CASE__ : List[Any] =orig_key.replace('''model.''', '''''' ) if "norm1" in orig_key: SCREAMING_SNAKE_CASE__ : Tuple =orig_key.replace('''norm1''', '''attention.output.LayerNorm''' ) if "norm2" in orig_key: SCREAMING_SNAKE_CASE__ : Optional[Any] =orig_key.replace('''norm2''', '''output.LayerNorm''' ) if "norm" in orig_key: SCREAMING_SNAKE_CASE__ : Dict =orig_key.replace('''norm''', '''LayerNorm''' ) if "transformer" in orig_key: SCREAMING_SNAKE_CASE__ : Union[str, Any] =orig_key.split('''.''' )[0].split('''_''' )[-1] SCREAMING_SNAKE_CASE__ : Dict =orig_key.replace(f"transformer_{layer_num}", f"encoder.layer.{layer_num}" ) if "mha.attn" in orig_key: SCREAMING_SNAKE_CASE__ : Optional[int] =orig_key.replace('''mha.attn''', '''attention.self''' ) if "mha" in orig_key: SCREAMING_SNAKE_CASE__ : List[Any] =orig_key.replace('''mha''', '''attention''' ) if "W_q" in orig_key: SCREAMING_SNAKE_CASE__ : Any =orig_key.replace('''W_q''', '''self.query''' ) if "W_k" in orig_key: SCREAMING_SNAKE_CASE__ : Tuple =orig_key.replace('''W_k''', '''self.key''' ) if "W_v" in orig_key: SCREAMING_SNAKE_CASE__ : Any =orig_key.replace('''W_v''', '''self.value''' ) if "ff1" in orig_key: SCREAMING_SNAKE_CASE__ : Any =orig_key.replace('''ff1''', '''intermediate.dense''' ) if "ff2" in orig_key: SCREAMING_SNAKE_CASE__ : List[Any] =orig_key.replace('''ff2''', '''output.dense''' ) if "ff" in orig_key: SCREAMING_SNAKE_CASE__ : Union[str, Any] =orig_key.replace('''ff''', '''output.dense''' ) if "mlm_class" in orig_key: SCREAMING_SNAKE_CASE__ : Optional[int] =orig_key.replace('''mlm.mlm_class''', '''cls.predictions.decoder''' ) if "mlm" in orig_key: SCREAMING_SNAKE_CASE__ : int =orig_key.replace('''mlm''', '''cls.predictions.transform''' ) if "cls" not in orig_key: SCREAMING_SNAKE_CASE__ : Optional[int] ='''yoso.''' + orig_key return orig_key def _a( UpperCamelCase__ : List[Any], UpperCamelCase__ : str ): '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : List[str] =orig_state_dict.pop(UpperCamelCase__ ) if ("pooler" in key) or ("sen_class" in key): continue else: SCREAMING_SNAKE_CASE__ : Optional[int] =val SCREAMING_SNAKE_CASE__ : Dict =orig_state_dict['''cls.predictions.decoder.bias'''] SCREAMING_SNAKE_CASE__ : Optional[int] =torch.arange(UpperCamelCase__ ).expand((1, -1) ) + 2 return orig_state_dict def _a( UpperCamelCase__ : List[Any], UpperCamelCase__ : Tuple, UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(UpperCamelCase__, map_location='''cpu''' )['''model_state_dict'''] SCREAMING_SNAKE_CASE__ : Optional[int] =YosoConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =YosoForMaskedLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =convert_checkpoint_helper(config.max_position_embeddings, UpperCamelCase__ ) print(model.load_state_dict(UpperCamelCase__ ) ) model.eval() model.save_pretrained(UpperCamelCase__ ) print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to YOSO pytorch checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for YOSO model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
665
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
1
'''simple docstring''' import torch from diffusers import DiffusionPipeline class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Union[str, Any] ) -> Union[str, Any]: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase ) def __call__( self : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) SCREAMING_SNAKE_CASE__ : Dict =1 SCREAMING_SNAKE_CASE__ : List[str] =self.unet(__lowercase , __lowercase ).sample SCREAMING_SNAKE_CASE__ : List[str] =self.scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample SCREAMING_SNAKE_CASE__ : Any =scheduler_output - scheduler_output + torch.ones_like(__lowercase ) return result
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): a_ = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right a_ = 1_2_8_0_2_2 a_ = 1_2_8_0_2_8 @require_sentencepiece class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = MaMaaaTokenizer snake_case_ = False snake_case_ = False snake_case_ = True def __magic_name__ ( self : Dict ) -> Union[str, Any]: super().setUp() SCREAMING_SNAKE_CASE__ : Dict =['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] SCREAMING_SNAKE_CASE__ : Any =dict(zip(__lowercase , range(len(__lowercase ) ) ) ) SCREAMING_SNAKE_CASE__ : int =Path(self.tmpdirname ) save_json(__lowercase , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__lowercase , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) SCREAMING_SNAKE_CASE__ : List[str] =MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Any , **__lowercase : Dict ) -> int: return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def __magic_name__ ( self : Tuple , __lowercase : Any ) -> Any: return ( "This is a test", "This is a test", ) def __magic_name__ ( self : Optional[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple ='''</s>''' SCREAMING_SNAKE_CASE__ : Any =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : List[Any] ) -> str: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] =list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(__lowercase ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def __magic_name__ ( self : List[Any] ) -> Union[str, Any]: pass def __magic_name__ ( self : Tuple ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [2, 3, 4, 5, 6] , ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(__lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_string(__lowercase ) self.assertEqual(__lowercase , '''This is a test''' ) @slow def __magic_name__ ( self : str ) -> List[Any]: # fmt: off SCREAMING_SNAKE_CASE__ : str ={'''input_ids''': [[12_80_22, 11_01_08, 3_97, 11, 3_82_72, 22_47, 12_48_11, 2_85, 1_81_05, 15_86, 2_07, 7, 3_95_34, 44_28, 3_97, 10_19, 1_81_05, 15_86, 2_07, 7, 4_13_37, 1_67_86, 2_41, 7, 2_02_14, 17, 12_56_90, 1_03_98, 7, 4_43_78, 5_80_69, 6_83_42, 77_98, 73_43, 11, 2_99, 3_33_10, 4, 1_58, 3_73_50, 9_40_77, 45_69, 2_99, 3_33_10, 90, 4, 5_28_40, 2_90, 4, 3_12_70, 1_12, 2_99, 6_82, 4, 5_28_40, 3_99_53, 1_40_79, 1_93, 5_25_19, 9_08_94, 1_78_94, 12_06_97, 11, 4_04_45, 5_51, 17, 10_19, 5_25_19, 9_08_94, 1_77_56, 9_63, 11, 4_04_45, 4_80, 17, 97_92, 11_20, 51_73, 13_93, 62_40, 1_67_86, 2_41, 12_09_96, 28, 12_45, 13_93, 11_82_40, 1_11_23, 10_19, 9_36_12, 26_91, 1_06_18, 9_80_58, 12_04_09, 19_28, 2_79, 4, 4_06_83, 3_67, 1_78, 2_07, 10_19, 1_03, 10_31_21, 5_06, 6_52_96, 5, 2], [12_80_22, 2_12_17, 3_67, 1_17, 12_54_50, 1_28, 7_19, 7, 73_08, 40, 9_36_12, 1_26_69, 11_16, 1_67_04, 71, 1_77_85, 36_99, 1_55_92, 35, 1_44, 95_84, 2_41, 1_19_43, 7_13, 9_50, 7_99, 22_47, 8_84_27, 1_50, 1_49, 11_88_13, 12_07_06, 10_19, 10_69_06, 8_15_18, 28, 12_24, 2_27_99, 3_97, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [12_80_22, 16_58, 12_33_11, 51_55, 55_78, 47_22, 2_79, 1_49_47, 23_66, 11_20, 11_97, 14, 13_48, 92_32, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = """facebook/m2m100_418M""" snake_case_ = [ """In my opinion, there are two levels of response from the French government.""", """NSA Affair Emphasizes Complete Lack of Debate on Intelligence""", ] snake_case_ = [ """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", ] # fmt: off snake_case_ = [EN_CODE, 593, 1949, 11_5781, 4, 7_1586, 4234, 6_0633, 12_6233, 432, 12_3808, 1_5592, 1197, 11_7132, 12_0618, 5, 2] @classmethod def __magic_name__ ( cls : int ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : MaMaaaTokenizer =MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) SCREAMING_SNAKE_CASE__ : Tuple =1 return cls def __magic_name__ ( self : Tuple ) -> Tuple: self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 12_80_06 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 12_80_22 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 12_80_76 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 12_80_63 ) def __magic_name__ ( self : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : List[Any] =self.tokenizer.get_vocab() self.assertEqual(len(__lowercase ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , __lowercase ) def __magic_name__ ( self : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''en''' SCREAMING_SNAKE_CASE__ : List[str] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowercase ) def __magic_name__ ( self : str ) -> Dict: self.assertIn(__lowercase , self.tokenizer.all_special_ids ) # fmt: off SCREAMING_SNAKE_CASE__ : Tuple =[FR_CODE, 53_64, 82, 86_42, 4, 2_94, 47, 8, 1_40_28, 1_36, 32_86, 97_06, 6, 9_07_97, 6, 14_40_12, 1_62, 8_81_28, 3_00_61, 5, 2] # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =self.tokenizer.decode(__lowercase , skip_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowercase ) self.assertEqual(__lowercase , __lowercase ) self.assertNotIn(self.tokenizer.eos_token , __lowercase ) def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[str] =tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[Any] =self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(__lowercase ) SCREAMING_SNAKE_CASE__ : int =MaMaaaTokenizer.from_pretrained(__lowercase ) self.assertDictEqual(new_tok.lang_token_to_id , __lowercase ) @require_torch def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] ='''en''' SCREAMING_SNAKE_CASE__ : Tuple ='''fr''' SCREAMING_SNAKE_CASE__ : Optional[Any] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowercase , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: SCREAMING_SNAKE_CASE__ : Dict =batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def __magic_name__ ( self : int ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Tuple ='''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) SCREAMING_SNAKE_CASE__ : int ='''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def __magic_name__ ( self : str ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] ='''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) SCREAMING_SNAKE_CASE__ : Dict ='''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def __magic_name__ ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(__lowercase ) , { # en_XX, A, test, EOS '''input_ids''': [[12_80_22, 58, 41_83, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 12_80_06, } , )
665
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
1
'''simple docstring''' a_ = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] ={'''I''': 1, '''V''': 5, '''X''': 1_0, '''L''': 5_0, '''C''': 1_0_0, '''D''': 5_0_0, '''M''': 1_0_0_0} SCREAMING_SNAKE_CASE__ : Dict =0 SCREAMING_SNAKE_CASE__ : int =0 while place < len(UpperCamelCase__ ): if (place + 1 < len(UpperCamelCase__ )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Optional[Any] =divmod(UpperCamelCase__, UpperCamelCase__ ) result.append(roman * factor ) if number == 0: break return "".join(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a_ = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _a( UpperCamelCase__ : str, UpperCamelCase__ : Tuple, UpperCamelCase__ : Any, UpperCamelCase__ : List[str], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase__ ) as metadata_file: SCREAMING_SNAKE_CASE__ : Optional[int] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =LukeConfig(use_entity_aware_attention=UpperCamelCase__, **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(UpperCamelCase__, map_location='''cpu''' )['''module'''] # Load the entity vocab file SCREAMING_SNAKE_CASE__ : List[str] =load_original_entity_vocab(UpperCamelCase__ ) # add an entry for [MASK2] SCREAMING_SNAKE_CASE__ : Optional[int] =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 SCREAMING_SNAKE_CASE__ : Optional[int] =XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken('''<ent>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =AddedToken('''<ent2>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int ='''MLukeTokenizer''' with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE__ : str =tokenizer.convert_tokens_to_ids(['''@'''] )[0] SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.convert_tokens_to_ids(['''#'''] )[0] SCREAMING_SNAKE_CASE__ : Dict =state_dict['''embeddings.word_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : List[str] =word_emb[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Tuple =word_emb[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[bias_name] SCREAMING_SNAKE_CASE__ : List[Any] =decoder_bias[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =decoder_bias[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE__ : Tuple =f"encoder.layer.{layer_index}.attention.self." SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : List[Any] =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE__ : Any =state_dict['''entity_embeddings.entity_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : Any =entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict['''entity_predictions.bias'''] SCREAMING_SNAKE_CASE__ : Tuple =entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_prediction_bias, entity_mask_bias] ) SCREAMING_SNAKE_CASE__ : int =LukeForMaskedLM(config=UpperCamelCase__ ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) SCREAMING_SNAKE_CASE__ : Tuple =OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[key] else: SCREAMING_SNAKE_CASE__ : Any =state_dict[key] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if set(UpperCamelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(f"Unexpected unexpected_keys: {unexpected_keys}" ) if set(UpperCamelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs SCREAMING_SNAKE_CASE__ : Any =MLukeTokenizer.from_pretrained(UpperCamelCase__, task='''entity_classification''' ) SCREAMING_SNAKE_CASE__ : str ='''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =(0, 9) SCREAMING_SNAKE_CASE__ : str =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =model(**UpperCamelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : str =torch.Size((1, 3_3, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : Any =torch.Size((1, 1, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" f" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify masked word/entity prediction SCREAMING_SNAKE_CASE__ : str =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''Tokyo is the capital of <mask>.''' SCREAMING_SNAKE_CASE__ : Dict =(2_4, 3_0) SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[str] =model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =encoding['''input_ids'''][0].tolist() SCREAMING_SNAKE_CASE__ : Any =input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.entity_logits[0][0].argmax().item() SCREAMING_SNAKE_CASE__ : Dict =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(UpperCamelCase__ ) ) model.save_pretrained(UpperCamelCase__ ) def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =['''[MASK]''', '''[PAD]''', '''[UNK]'''] SCREAMING_SNAKE_CASE__ : List[str] =[json.loads(UpperCamelCase__ ) for line in open(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Optional[int] ={} for entry in data: SCREAMING_SNAKE_CASE__ : Tuple =entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: SCREAMING_SNAKE_CASE__ : str =entity_id break SCREAMING_SNAKE_CASE__ : Union[str, Any] =f"{language}:{entity_name}" SCREAMING_SNAKE_CASE__ : Union[str, Any] =entity_id return new_mapping if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a_ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
665
1
'''simple docstring''' a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def _a( UpperCamelCase__ : dict, UpperCamelCase__ : List[Any], UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE__ : Union[str, Any] =[[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE__ : List[Any] =queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE__ : Optional[int] =path[-1] if node not in explored: SCREAMING_SNAKE_CASE__ : Union[str, Any] =graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE__ : Union[str, Any] =list(UpperCamelCase__ ) new_path.append(UpperCamelCase__ ) queue.append(UpperCamelCase__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(UpperCamelCase__ ) # in case there's no path between the 2 nodes return [] def _a( UpperCamelCase__ : dict, UpperCamelCase__ : Tuple, UpperCamelCase__ : str ): '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE__ : Optional[Any] =[start] SCREAMING_SNAKE_CASE__ : Tuple =set(UpperCamelCase__ ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE__ : Tuple ={start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE__ : Optional[Any] =queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE__ : List[Any] =( dist[node] if dist[target] == -1 else min(dist[target], dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(UpperCamelCase__ ) queue.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
665
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : List[Any] =True for i in range(UpperCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE__ : Optional[int] =True if a[i].islower(): SCREAMING_SNAKE_CASE__ : List[Any] =True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ('''cls_token''', '''vit.embeddings.cls_token'''), ('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE__ : Tuple =[(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ : List[Any] ='''''' else: SCREAMING_SNAKE_CASE__ : Optional[int] ='''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : List[Any] =state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int =in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : str =in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : str =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : str =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] =in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Dict =in_proj_bias[-config.hidden_size :] def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(UpperCamelCase__, UpperCamelCase__ ) def _a( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : str, UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =val def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE__ : List[Any] =Image.open(requests.get(UpperCamelCase__, stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def _a( UpperCamelCase__ : int, UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =ViTConfig() SCREAMING_SNAKE_CASE__ : int =False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =int(vit_name[-1_2:-1_0] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =int(vit_name[-9:-6] ) else: SCREAMING_SNAKE_CASE__ : Any =1_0_0_0 SCREAMING_SNAKE_CASE__ : List[Any] ='''huggingface/label-files''' SCREAMING_SNAKE_CASE__ : int ='''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE__ : List[Any] =json.load(open(hf_hub_download(UpperCamelCase__, UpperCamelCase__, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE__ : List[str] ={int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : int =idalabel SCREAMING_SNAKE_CASE__ : str ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[Any] =int(vit_name[-6:-4] ) SCREAMING_SNAKE_CASE__ : int =int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('''tiny''' ): SCREAMING_SNAKE_CASE__ : Optional[int] =1_9_2 SCREAMING_SNAKE_CASE__ : Dict =7_6_8 SCREAMING_SNAKE_CASE__ : Optional[int] =1_2 SCREAMING_SNAKE_CASE__ : Tuple =3 elif vit_name[9:].startswith('''small''' ): SCREAMING_SNAKE_CASE__ : Any =3_8_4 SCREAMING_SNAKE_CASE__ : Any =1_5_3_6 SCREAMING_SNAKE_CASE__ : Any =1_2 SCREAMING_SNAKE_CASE__ : Union[str, Any] =6 else: pass else: if vit_name[4:].startswith('''small''' ): SCREAMING_SNAKE_CASE__ : str =7_6_8 SCREAMING_SNAKE_CASE__ : Optional[int] =2_3_0_4 SCREAMING_SNAKE_CASE__ : List[str] =8 SCREAMING_SNAKE_CASE__ : List[Any] =8 elif vit_name[4:].startswith('''base''' ): pass elif vit_name[4:].startswith('''large''' ): SCREAMING_SNAKE_CASE__ : str =1_0_2_4 SCREAMING_SNAKE_CASE__ : Optional[Any] =4_0_9_6 SCREAMING_SNAKE_CASE__ : Optional[Any] =2_4 SCREAMING_SNAKE_CASE__ : Dict =1_6 elif vit_name[4:].startswith('''huge''' ): SCREAMING_SNAKE_CASE__ : List[Any] =1_2_8_0 SCREAMING_SNAKE_CASE__ : int =5_1_2_0 SCREAMING_SNAKE_CASE__ : Tuple =3_2 SCREAMING_SNAKE_CASE__ : int =1_6 # load original model from timm SCREAMING_SNAKE_CASE__ : str =timm.create_model(UpperCamelCase__, pretrained=UpperCamelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Optional[int] =timm_model.state_dict() if base_model: remove_classification_head_(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =create_rename_keys(UpperCamelCase__, UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) read_in_q_k_v(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE__ : List[str] =ViTModel(UpperCamelCase__ ).eval() else: SCREAMING_SNAKE_CASE__ : Dict =ViTForImageClassification(UpperCamelCase__ ).eval() model.load_state_dict(UpperCamelCase__ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: SCREAMING_SNAKE_CASE__ : Optional[Any] =DeiTImageProcessor(size=config.image_size ) else: SCREAMING_SNAKE_CASE__ : Any =ViTImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] =image_processor(images=prepare_img(), return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : Dict =encoding['''pixel_values'''] SCREAMING_SNAKE_CASE__ : Any =model(UpperCamelCase__ ) if base_model: SCREAMING_SNAKE_CASE__ : str =timm_model.forward_features(UpperCamelCase__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(UpperCamelCase__, outputs.pooler_output, atol=1e-3 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =timm_model(UpperCamelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCamelCase__, outputs.logits, atol=1e-3 ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(UpperCamelCase__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) a_ = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
665
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[Any] , __lowercase : List[str]=13 , __lowercase : int=7 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : List[Any]=True , __lowercase : str=True , __lowercase : Tuple=99 , __lowercase : Union[str, Any]=64 , __lowercase : Tuple=32 , __lowercase : Optional[Any]=5 , __lowercase : Tuple=4 , __lowercase : Optional[int]=37 , __lowercase : int="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : List[Any]=0.1 , __lowercase : List[Any]=5_12 , __lowercase : int=16 , __lowercase : Optional[int]=2 , __lowercase : Tuple=0.02 , __lowercase : List[str]=3 , __lowercase : List[str]=4 , __lowercase : List[str]=None , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =seq_length SCREAMING_SNAKE_CASE__ : Dict =is_training SCREAMING_SNAKE_CASE__ : List[Any] =use_input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] =use_labels SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : str =hidden_size SCREAMING_SNAKE_CASE__ : Any =embedding_size SCREAMING_SNAKE_CASE__ : Tuple =num_hidden_layers SCREAMING_SNAKE_CASE__ : str =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : Any =type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE__ : str =num_labels SCREAMING_SNAKE_CASE__ : List[str] =num_choices SCREAMING_SNAKE_CASE__ : List[str] =scope def __magic_name__ ( self : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : int =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =None SCREAMING_SNAKE_CASE__ : Optional[Any] =None SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : List[str] ) -> Any: return MegatronBertConfig( 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 , embedding_size=self.embedding_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=__lowercase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Any , __lowercase : Tuple , __lowercase : Any , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ ( self : Dict , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : Any , __lowercase : Optional[int] , __lowercase : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =MegatronBertForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : List[str] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : str , __lowercase : Any , __lowercase : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =MegatronBertForNextSentencePrediction(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : List[str] , __lowercase : Optional[int] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForPreTraining(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , next_sentence_label=__lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any , __lowercase : Any , __lowercase : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =MegatronBertForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __magic_name__ ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : int , __lowercase : List[str] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.num_labels SCREAMING_SNAKE_CASE__ : Dict =MegatronBertForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple =self.num_labels SCREAMING_SNAKE_CASE__ : int =MegatronBertForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : Dict , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Any , __lowercase : List[Any] , __lowercase : int , __lowercase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.num_choices SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[int] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : str ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True # test_resize_embeddings = False snake_case_ = False def __magic_name__ ( self : List[Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : Tuple=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str ) -> Dict: self.config_tester.run_common_tests() def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowercase ) def __magic_name__ ( self : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowercase ) def __magic_name__ ( self : Dict ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowercase ) def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' return torch.tensor( UpperCamelCase__, dtype=torch.long, device=UpperCamelCase__, ) a_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow @unittest.skip('''Model is not available.''' ) def __magic_name__ ( self : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any ='''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ : Optional[int] =os.path.join(os.environ['''MYDIR'''] , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =MegatronBertModel.from_pretrained(__lowercase ) model.to(__lowercase ) model.half() SCREAMING_SNAKE_CASE__ : Dict =_long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase )[0] SCREAMING_SNAKE_CASE__ : Dict =torch.Size((1, 9, 10_24) ) self.assertEqual(output.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : str =[-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ : List[Any] =output[0, ii, jj] SCREAMING_SNAKE_CASE__ : Tuple =expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ : List[str] ='''ii={} jj={} a={} b={}'''.format(__lowercase , __lowercase , __lowercase , __lowercase ) self.assertTrue(math.isclose(__lowercase , __lowercase , rel_tol=__lowercase , abs_tol=__lowercase ) , msg=__lowercase )
665
1
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() SCREAMING_SNAKE_CASE__ : List[str] =[sys.executable] + distributed_args execute_subprocess_async(__lowercase , env=os.environ.copy() )
665
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() SCREAMING_SNAKE_CASE__ : List[str] =[sys.executable] + distributed_args execute_subprocess_async(__lowercase , env=os.environ.copy() )
665
1
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) a_ = 2_9_9_7_9_2_4_5_8 # Symbols a_ , a_ , a_ , a_ = symbols('ct x y z') def _a( UpperCamelCase__ : float ): '''simple docstring''' if velocity > c: raise ValueError('''Speed must not exceed light speed 299,792,458 [m/s]!''' ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError('''Speed must be greater than or equal to 1!''' ) return velocity / c def _a( UpperCamelCase__ : float ): '''simple docstring''' return 1 / sqrt(1 - beta(UpperCamelCase__ ) ** 2 ) def _a( UpperCamelCase__ : float ): '''simple docstring''' return np.array( [ [gamma(UpperCamelCase__ ), -gamma(UpperCamelCase__ ) * beta(UpperCamelCase__ ), 0, 0], [-gamma(UpperCamelCase__ ) * beta(UpperCamelCase__ ), gamma(UpperCamelCase__ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def _a( UpperCamelCase__ : float, UpperCamelCase__ : np.ndarray | None = None ): '''simple docstring''' if event is None: SCREAMING_SNAKE_CASE__ : Optional[Any] =np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(UpperCamelCase__ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: a_ = transform(2_9_9_7_9_2_4_5) print('Example of four vector: ') print(F'''ct\' = {four_vector[0]}''') print(F'''x\' = {four_vector[1]}''') print(F'''y\' = {four_vector[2]}''') print(F'''z\' = {four_vector[3]}''') # Substitute symbols with numerical values a_ = {ct: c, x: 1, y: 1, z: 1} a_ = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = ShapEImgaImgPipeline snake_case_ = ["""image"""] snake_case_ = ["""image"""] snake_case_ = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[Any] ) -> List[Any]: return 32 @property def __magic_name__ ( self : List[str] ) -> Optional[int]: return 32 @property def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: return self.time_input_dim * 4 @property def __magic_name__ ( self : Dict ) -> Union[str, Any]: return 8 @property def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) SCREAMING_SNAKE_CASE__ : str =CLIPVisionModel(__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =CLIPImageProcessor( crop_size=2_24 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __magic_name__ ( self : List[str] ) -> Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str ={ '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } SCREAMING_SNAKE_CASE__ : str =PriorTransformer(**__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE__ : str =ShapERenderer(**__lowercase ) return model def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.dummy_prior SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_encoder SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_processor SCREAMING_SNAKE_CASE__ : Tuple =self.dummy_renderer SCREAMING_SNAKE_CASE__ : int =HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=__lowercase , clip_sample=__lowercase , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ : Any ={ '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __magic_name__ ( self : Any , __lowercase : List[str] , __lowercase : Any=0 ) -> Any: SCREAMING_SNAKE_CASE__ : int =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : List[str] =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : List[str] ) -> str: SCREAMING_SNAKE_CASE__ : int ='''cpu''' SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : str =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] =np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __magic_name__ ( self : List[Any] ) -> List[str]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch_device == '''cpu''' SCREAMING_SNAKE_CASE__ : Optional[Any] =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowercase , relax_max_difference=__lowercase , ) def __magic_name__ ( self : Dict ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =1 SCREAMING_SNAKE_CASE__ : List[str] =2 SCREAMING_SNAKE_CASE__ : Dict =self.get_dummy_inputs(__lowercase ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ : Tuple =batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ : List[Any] =pipe(**__lowercase , num_images_per_prompt=__lowercase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Optional[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) SCREAMING_SNAKE_CASE__ : Dict =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) SCREAMING_SNAKE_CASE__ : List[Any] =ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) SCREAMING_SNAKE_CASE__ : Tuple =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple =pipe( __lowercase , generator=__lowercase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' while b: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =b, a % b return a def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(UpperCamelCase__, a % b ) def _a( ): '''simple docstring''' print(f"euclidean_gcd(3, 5) = {euclidean_gcd(3, 5 )}" ) print(f"euclidean_gcd(5, 3) = {euclidean_gcd(5, 3 )}" ) print(f"euclidean_gcd(1, 3) = {euclidean_gcd(1, 3 )}" ) print(f"euclidean_gcd(3, 6) = {euclidean_gcd(3, 6 )}" ) print(f"euclidean_gcd(6, 3) = {euclidean_gcd(6, 3 )}" ) print(f"euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3, 5 )}" ) print(f"euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5, 3 )}" ) print(f"euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1, 3 )}" ) print(f"euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3, 6 )}" ) print(f"euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6, 3 )}" ) if __name__ == "__main__": main()
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_bigcode""" snake_case_ = ["""past_key_values"""] snake_case_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Any , __lowercase : Any=5_02_57 , __lowercase : int=10_24 , __lowercase : List[str]=7_68 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : List[str]=None , __lowercase : int="gelu_pytorch_tanh" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=1e-5 , __lowercase : List[str]=0.02 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=5_02_56 , __lowercase : List[Any]=5_02_56 , __lowercase : Union[str, Any]=True , __lowercase : List[str]=True , __lowercase : Dict=True , **__lowercase : List[Any] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_positions SCREAMING_SNAKE_CASE__ : Dict =n_embd SCREAMING_SNAKE_CASE__ : Dict =n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_head SCREAMING_SNAKE_CASE__ : List[str] =n_inner SCREAMING_SNAKE_CASE__ : List[str] =activation_function SCREAMING_SNAKE_CASE__ : List[Any] =resid_pdrop SCREAMING_SNAKE_CASE__ : List[Any] =embd_pdrop SCREAMING_SNAKE_CASE__ : List[str] =attn_pdrop SCREAMING_SNAKE_CASE__ : Dict =layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =scale_attn_weights SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Dict =attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : int =scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Dict =multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] =eos_token_id super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase )
665
1
'''simple docstring''' from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
665
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =size SCREAMING_SNAKE_CASE__ : List[Any] =[0] * size SCREAMING_SNAKE_CASE__ : str =[0] * size @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return index | (index + 1) @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return (index & (index + 1)) - 1 def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =value while index < self.size: SCREAMING_SNAKE_CASE__ : Any =self.get_prev(__lowercase ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : List[str] =value else: SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_next(__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> int: right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : str =0 while left <= right: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_prev(__lowercase ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[Any] =max(__lowercase , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Any =current_left else: SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from __future__ import annotations import requests def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(UpperCamelCase__ ).json() def _a( UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str ='''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' SCREAMING_SNAKE_CASE__ : List[str] =requests.get(UpperCamelCase__ ).json()[:max_stories] return [get_hackernews_story(UpperCamelCase__ ) for story_id in story_ids] def _a( UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =hackernews_top_stories(UpperCamelCase__ ) return "\n".join('''* [{title}]({url})'''.format(**UpperCamelCase__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
665
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""vqvae"""] def __init__( self : int , __lowercase : AutoencoderKL , __lowercase : UNetaDConditionModel , __lowercase : Mel , __lowercase : Union[DDIMScheduler, DDPMScheduler] , ) -> int: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase , mel=__lowercase , vqvae=__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return 50 if isinstance(self.scheduler , __lowercase ) else 10_00 @torch.no_grad() def __call__( self : Dict , __lowercase : int = 1 , __lowercase : str = None , __lowercase : np.ndarray = None , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = None , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : float = 0 , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : torch.Tensor = None , __lowercase : torch.Tensor = None , __lowercase : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: SCREAMING_SNAKE_CASE__ : Optional[Any] =steps or self.get_default_steps() self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE__ : Optional[int] =randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowercase , device=self.device , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =noise SCREAMING_SNAKE_CASE__ : List[str] =None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.mel.audio_slice_to_image(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE__ : int =(input_image / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =self.vqvae.encode(torch.unsqueeze(__lowercase , 0 ) ).latent_dist.sample( generator=__lowercase )[0] SCREAMING_SNAKE_CASE__ : int =self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE__ : Optional[Any] =int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : Tuple =int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowercase ): SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase , __lowercase )['''sample'''] else: SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase )['''sample'''] if isinstance(self.scheduler , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , eta=__lowercase , generator=__lowercase , )['''prev_sample'''] else: SCREAMING_SNAKE_CASE__ : Any =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , generator=__lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE__ : List[str] =mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE__ : str =1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE__ : int =self.vqvae.decode(__lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE__ : Dict =(images * 2_55).round().astype('''uint8''' ) SCREAMING_SNAKE_CASE__ : Any =list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[self.mel.image_to_audio(__lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowercase ) ) @torch.no_grad() def __magic_name__ ( self : Optional[int] , __lowercase : List[Image.Image] , __lowercase : int = 50 ) -> np.ndarray: assert isinstance(self.scheduler , __lowercase ) self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE__ : str =(sample / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : str =torch.Tensor(__lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE__ : Tuple =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE__ : Any =self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : int =( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : int =1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Optional[Any] =self.unet(__lowercase , __lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =(1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE__ : str =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE__ : Any =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __magic_name__ ( __lowercase : torch.Tensor , __lowercase : torch.Tensor , __lowercase : float ) -> torch.Tensor: SCREAMING_SNAKE_CASE__ : Optional[int] =acos(torch.dot(torch.flatten(__lowercase ) , torch.flatten(__lowercase ) ) / torch.norm(__lowercase ) / torch.norm(__lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowercase ) + sin(alpha * theta ) * xa / sin(__lowercase )
665
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = (EulerDiscreteScheduler,) snake_case_ = 10 def __magic_name__ ( self : Union[str, Any] , **__lowercase : List[Any] ) -> str: SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 11_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**__lowercase ) return config def __magic_name__ ( self : int ) -> int: for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__lowercase ) def __magic_name__ ( self : Dict ) -> str: for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__lowercase , beta_end=__lowercase ) def __magic_name__ ( self : Optional[int] ) -> List[str]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Tuple =self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] =self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Optional[Any] =scheduler_class(**__lowercase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : str =sample.to(__lowercase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : int =scheduler.scale_model_input(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =scheduler.step(__lowercase , __lowercase , __lowercase , generator=__lowercase ) SCREAMING_SNAKE_CASE__ : str =output.prev_sample SCREAMING_SNAKE_CASE__ : List[str] =torch.sum(torch.abs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : int =torch.mean(torch.abs(__lowercase ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] =self.get_scheduler_config(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =scheduler_class(**__lowercase ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict =self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[int] =self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : List[Any] =sample.to(__lowercase ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =scheduler.scale_model_input(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =scheduler.step(__lowercase , __lowercase , __lowercase , generator=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.sum(torch.abs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Dict =torch.mean(torch.abs(__lowercase ) ) assert abs(result_sum.item() - 0.0002 ) < 1e-2 assert abs(result_mean.item() - 2.2676e-06 ) < 1e-3 def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] =self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] =scheduler_class(**__lowercase ) scheduler.set_timesteps(self.num_inference_steps , device=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple =self.dummy_model() SCREAMING_SNAKE_CASE__ : str =self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE__ : List[Any] =sample.to(__lowercase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : Optional[int] =scheduler.scale_model_input(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : str =scheduler.step(__lowercase , __lowercase , __lowercase , generator=__lowercase ) SCREAMING_SNAKE_CASE__ : int =output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] =torch.sum(torch.abs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.mean(torch.abs(__lowercase ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int =scheduler_class(**__lowercase , use_karras_sigmas=__lowercase ) scheduler.set_timesteps(self.num_inference_steps , device=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int =self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE__ : Tuple =sample.to(__lowercase ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : int =scheduler.scale_model_input(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : int =scheduler.step(__lowercase , __lowercase , __lowercase , generator=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =output.prev_sample SCREAMING_SNAKE_CASE__ : int =torch.sum(torch.abs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Any =torch.mean(torch.abs(__lowercase ) ) assert abs(result_sum.item() - 124.52299499511719 ) < 1e-2 assert abs(result_mean.item() - 0.16213932633399963 ) < 1e-3
665
'''simple docstring''' from math import isqrt def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Any =False return [i for i in range(2, UpperCamelCase__ ) if is_prime[i]] def _a( UpperCamelCase__ : int = 1_0**8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =calculate_prime_numbers(max_number // 2 ) SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __magic_name__ ( self : Any ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : str =tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Union[str, Any] =5 # Realm tok SCREAMING_SNAKE_CASE__ : Union[str, Any] =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE__ : Dict =os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(__lowercase , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =os.path.join(__lowercase , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(__lowercase , exist_ok=__lowercase ) def __magic_name__ ( self : Dict ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def __magic_name__ ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __magic_name__ ( self : int ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =RealmConfig(num_block_records=self.num_block_records ) return config def __magic_name__ ( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int =Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def __magic_name__ ( self : Any ) -> int: SCREAMING_SNAKE_CASE__ : Any =np.array( [ B'''This is the first record''', B'''This is the second record''', B'''This is the third record''', B'''This is the fourth record''', B'''This is the fifth record''', B'''This is a longer longer longer record''', ] , dtype=__lowercase , ) return block_records def __magic_name__ ( self : List[Any] ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] =RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __magic_name__ ( self : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() SCREAMING_SNAKE_CASE__ : Dict =self.get_dummy_retriever() SCREAMING_SNAKE_CASE__ : List[Any] =retriever.tokenizer SCREAMING_SNAKE_CASE__ : int =np.array([0, 3] , dtype='''long''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer(['''Test question'''] ).input_ids SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer( ['''the fourth'''] , add_special_tokens=__lowercase , return_token_type_ids=__lowercase , return_attention_mask=__lowercase , ).input_ids SCREAMING_SNAKE_CASE__ : Tuple =config.reader_seq_len SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =retriever( __lowercase , __lowercase , answer_ids=__lowercase , max_length=__lowercase , return_tensors='''np''' ) self.assertEqual(len(__lowercase ) , 2 ) self.assertEqual(len(__lowercase ) , 2 ) self.assertEqual(len(__lowercase ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =self.get_config() SCREAMING_SNAKE_CASE__ : str =self.get_dummy_retriever() SCREAMING_SNAKE_CASE__ : Dict =retriever.tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] =np.array([0, 3, 5] , dtype='''long''' ) SCREAMING_SNAKE_CASE__ : Dict =tokenizer(['''Test question'''] ).input_ids SCREAMING_SNAKE_CASE__ : Any =tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=__lowercase , return_token_type_ids=__lowercase , return_attention_mask=__lowercase , ).input_ids SCREAMING_SNAKE_CASE__ : int =config.reader_seq_len SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =retriever( __lowercase , __lowercase , answer_ids=__lowercase , max_length=__lowercase , return_tensors='''np''' ) self.assertEqual([False, True, True] , __lowercase ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __lowercase ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __lowercase ) def __magic_name__ ( self : List[Any] ) -> str: SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path SCREAMING_SNAKE_CASE__ : Any =retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , B'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: SCREAMING_SNAKE_CASE__ : Tuple =os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) SCREAMING_SNAKE_CASE__ : int =RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , B'''This is the first record''' )
665
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = SpeechTaTokenizer snake_case_ = False snake_case_ = True def __magic_name__ ( self : int ) -> Any: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[Any] =SpeechTaTokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken('''<mask>''' , lstrip=__lowercase , rstrip=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Dict , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''this is a test''' SCREAMING_SNAKE_CASE__ : int ='''this is a test''' return input_text, output_text def __magic_name__ ( self : List[Any] , __lowercase : int , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=20 , __lowercase : Any=5 ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_input_output_texts(__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.decode(__lowercase , clean_up_tokenization_spaces=__lowercase ) return text, ids def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] ='''<pad>''' SCREAMING_SNAKE_CASE__ : Optional[int] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__lowercase ) , 81 ) def __magic_name__ ( self : Dict ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Any =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ : int =['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.add_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ : str ={'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} SCREAMING_SNAKE_CASE__ : int =tokenizer.add_special_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size_a + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __magic_name__ ( self : Optional[Any] ) -> Any: pass def __magic_name__ ( self : List[str] ) -> List[Any]: pass def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_ids(__lowercase ) # fmt: off self.assertListEqual(__lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.convert_ids_to_tokens(__lowercase ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __magic_name__ ( self : List[str] ) -> List[str]: # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE__ : List[Any] =[ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off SCREAMING_SNAKE_CASE__ : str ={ '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__lowercase , )
665
1
'''simple docstring''' import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = GPTaTokenizer snake_case_ = GPTaTokenizerFast snake_case_ = True snake_case_ = {"""add_prefix_space""": True} snake_case_ = False def __magic_name__ ( self : Any ) -> Tuple: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : List[Any] =[ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', '''<|endoftext|>''', ] SCREAMING_SNAKE_CASE__ : Any =dict(zip(__lowercase , range(len(__lowercase ) ) ) ) SCREAMING_SNAKE_CASE__ : Any =['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE__ : Tuple ={'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE__ : List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__lowercase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowercase ) ) def __magic_name__ ( self : Any , **__lowercase : Optional[Any] ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def __magic_name__ ( self : int , **__lowercase : Optional[Any] ) -> Tuple: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **__lowercase ) def __magic_name__ ( self : List[str] , __lowercase : Tuple ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any ='''lower newer''' SCREAMING_SNAKE_CASE__ : List[str] ='''lower newer''' return input_text, output_text def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple ='''lower newer''' SCREAMING_SNAKE_CASE__ : List[str] =['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Optional[Any] =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> Union[str, Any]: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : List[str] =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple =self.get_rust_tokenizer(add_prefix_space=__lowercase ) SCREAMING_SNAKE_CASE__ : int ='''lower newer''' # Testing tokenization SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =rust_tokenizer.tokenize(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.encode(__lowercase , add_special_tokens=__lowercase , add_prefix_space=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =rust_tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : Optional[int] =self.get_rust_tokenizer(add_prefix_space=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode(__lowercase , add_prefix_space=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =rust_tokenizer.encode(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : Dict =tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Union[str, Any] =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def __magic_name__ ( self : Union[str, Any] , *__lowercase : Tuple , **__lowercase : Dict ) -> Tuple: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def __magic_name__ ( self : Optional[int] , __lowercase : List[str]=15 ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.rust_tokenizer_class.from_pretrained(__lowercase , **__lowercase ) # Simple input SCREAMING_SNAKE_CASE__ : Dict ='''This is a simple input''' SCREAMING_SNAKE_CASE__ : List[Any] =['''This is a simple input 1''', '''This is a simple input 2'''] SCREAMING_SNAKE_CASE__ : Optional[Any] =('''This is a simple input''', '''This is a pair''') SCREAMING_SNAKE_CASE__ : List[str] =[ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding='''max_length''' ) # Simple input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding='''max_length''' ) # Simple input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding='''max_length''' , ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding='''max_length''' ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding='''max_length''' ) # Pair input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding='''max_length''' , ) def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[str] =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='''<pad>''' ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[int] ='''This is a simple input''' SCREAMING_SNAKE_CASE__ : str =['''This is a simple input looooooooong''', '''This is a simple input'''] SCREAMING_SNAKE_CASE__ : List[Any] =('''This is a simple input''', '''This is a pair''') SCREAMING_SNAKE_CASE__ : Optional[int] =[ ('''This is a simple input loooooong''', '''This is a simple input'''), ('''This is a simple pair loooooong''', '''This is a simple pair'''), ] SCREAMING_SNAKE_CASE__ : Dict =tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer(__lowercase , padding='''max_length''' , max_length=30 , return_tensors='''np''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors='''np''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(*__lowercase , padding='''max_length''' , max_length=60 , return_tensors='''np''' ) SCREAMING_SNAKE_CASE__ : Any =tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors='''np''' ) # s # test single string max_length padding self.assertEqual(out_s['''input_ids'''].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['''input_ids'''] ) self.assertTrue(0 in out_s['''attention_mask'''] ) # s2 # test automatic padding self.assertEqual(out_sa['''input_ids'''].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['''input_ids'''][0] ) self.assertFalse(0 in out_sa['''attention_mask'''][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['''input_ids'''][1] ) self.assertTrue(0 in out_sa['''attention_mask'''][1] ) # p # test single pair max_length padding self.assertEqual(out_p['''input_ids'''].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['''input_ids'''] ) self.assertTrue(0 in out_p['''attention_mask'''] ) # p2 # test automatic padding pair self.assertEqual(out_pa['''input_ids'''].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['''input_ids'''][0] ) self.assertFalse(0 in out_pa['''attention_mask'''][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['''input_ids'''][1] ) self.assertTrue(0 in out_pa['''attention_mask'''][1] ) def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Dict ='''$$$''' SCREAMING_SNAKE_CASE__ : List[Any] =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=__lowercase , add_bos_token=__lowercase ) SCREAMING_SNAKE_CASE__ : int ='''This is a simple input''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =['''This is a simple input 1''', '''This is a simple input 2'''] SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =tokenizer(__lowercase ) self.assertEqual(out_s.input_ids[0] , __lowercase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : Any =tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __lowercase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def __magic_name__ ( self : Tuple ) -> List[Any]: pass def __magic_name__ ( self : Any ) -> int: # TODO: change to self.get_tokenizers() when the fast version is implemented SCREAMING_SNAKE_CASE__ : Dict =[self.get_tokenizer(do_lower_case=__lowercase , add_bos_token=__lowercase )] for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : List[str] ='''Encode this.''' SCREAMING_SNAKE_CASE__ : List[Any] ='''This one too please.''' SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) encoded_sequence += tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.encode_plus( __lowercase , __lowercase , add_special_tokens=__lowercase , return_special_tokens_mask=__lowercase , ) SCREAMING_SNAKE_CASE__ : Any =encoded_sequence_dict['''input_ids'''] SCREAMING_SNAKE_CASE__ : Tuple =encoded_sequence_dict['''special_tokens_mask'''] self.assertEqual(len(__lowercase ) , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(__lowercase ) ] SCREAMING_SNAKE_CASE__ : int =[x for x in filtered_sequence if x is not None] self.assertEqual(__lowercase , __lowercase ) @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : List[Any] ) -> Tuple: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 SCREAMING_SNAKE_CASE__ : List[str] =AutoTokenizer.from_pretrained('''facebook/opt-350m''' , from_slow=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] ='''A photo of a cat''' SCREAMING_SNAKE_CASE__ : Dict =tokenizer.encode( __lowercase , ) self.assertEqual(__lowercase , [2, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained('''test_opt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =AutoTokenizer.from_pretrained('''./test_opt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( __lowercase , ) self.assertEqual(__lowercase , [2, 2_50, 13_45, 9, 10, 47_58] ) def __magic_name__ ( self : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[str] =AutoTokenizer.from_pretrained('''facebook/opt-350m''' , use_slow=__lowercase ) SCREAMING_SNAKE_CASE__ : int ='''A photo of a cat''' SCREAMING_SNAKE_CASE__ : Any =tokenizer.encode( __lowercase , ) # Same as above self.assertEqual(__lowercase , [2, 2_50, 13_45, 9, 10, 47_58] ) @unittest.skip('''This test is failing because of a bug in the fast tokenizer''' ) def __magic_name__ ( self : List[str] ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[Any] =AutoTokenizer.from_pretrained('''facebook/opt-350m''' , from_slow=__lowercase ) SCREAMING_SNAKE_CASE__ : str ='''bos''' SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.get_vocab()['''bos'''] SCREAMING_SNAKE_CASE__ : Any ='''A photo of a cat''' SCREAMING_SNAKE_CASE__ : Any =tokenizer.encode( __lowercase , ) # We changed the bos token self.assertEqual(__lowercase , [3_19_57, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained('''./tok''' ) SCREAMING_SNAKE_CASE__ : List[Any] =AutoTokenizer.from_pretrained('''./tok''' ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode( __lowercase , ) self.assertEqual(__lowercase , [3_19_57, 2_50, 13_45, 9, 10, 47_58] )
665
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
1
'''simple docstring''' import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] , __lowercase : int , __lowercase : List[Any]=1_00 , __lowercase : Optional[int]=13 , __lowercase : Union[str, Any]=30 , __lowercase : List[Any]=2 , __lowercase : Any=3 , __lowercase : List[Any]=True , __lowercase : Any=True , __lowercase : Optional[Any]=32 , __lowercase : Tuple=4 , __lowercase : str=4 , __lowercase : Optional[Any]=37 , __lowercase : Union[str, Any]="gelu" , __lowercase : List[str]=0.1 , __lowercase : Union[str, Any]=0.1 , __lowercase : Any=10 , __lowercase : Optional[Any]=0.02 , __lowercase : Union[str, Any]=3 , __lowercase : Union[str, Any]=None , __lowercase : Tuple=[0, 1, 2, 3] , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Dict =parent SCREAMING_SNAKE_CASE__ : Dict =1_00 SCREAMING_SNAKE_CASE__ : Dict =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : str =patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =num_channels SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : Any =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : str =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[Any] =initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] =scope SCREAMING_SNAKE_CASE__ : Optional[int] =out_indices SCREAMING_SNAKE_CASE__ : Any =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Tuple =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Dict =num_patches + 1 def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict =None SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() return config, pixel_values, labels, pixel_labels def __magic_name__ ( self : Any ) -> int: return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowercase , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def __magic_name__ ( self : List[Any] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : Optional[Any] , __lowercase : Any ) -> str: SCREAMING_SNAKE_CASE__ : Optional[Any] =BeitModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Any , __lowercase : List[str] , __lowercase : str , __lowercase : List[str] , __lowercase : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : str =BeitForMaskedImageModeling(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __magic_name__ ( self : Tuple , __lowercase : Optional[int] , __lowercase : Any , __lowercase : Any , __lowercase : Tuple ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple =self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] =BeitForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Tuple =1 SCREAMING_SNAKE_CASE__ : Tuple =BeitForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __magic_name__ ( self : List[str] , __lowercase : Optional[Any] , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.num_labels SCREAMING_SNAKE_CASE__ : str =BeitForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": BeitModel, """image-classification""": BeitForImageClassification, """image-segmentation""": BeitForSemanticSegmentation, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] =BeitModelTester(self ) SCREAMING_SNAKE_CASE__ : str =ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : int ) -> int: self.config_tester.run_common_tests() @unittest.skip(reason='''BEiT does not use inputs_embeds''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason='''BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __magic_name__ ( self : Tuple ) -> Any: pass def __magic_name__ ( self : Optional[int] ) -> List[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Dict =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[Any] =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : Dict ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[Any]: if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(__lowercase ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE__ : Tuple =model_class(__lowercase ) model.to(__lowercase ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] =self._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ).loss loss.backward() def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : int =False SCREAMING_SNAKE_CASE__ : str =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(__lowercase ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE__ : Optional[int] =model_class(__lowercase ) model.gradient_checkpointing_enable() model.to(__lowercase ) model.train() SCREAMING_SNAKE_CASE__ : str =self._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =model(**__lowercase ).loss loss.backward() def __magic_name__ ( self : Union[str, Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] =_config_zero_init(__lowercase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(config=__lowercase ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @slow def __magic_name__ ( self : Dict ) -> str: for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =BeitModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : List[Any] ) -> Dict: return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''' ) if is_vision_available() else None @slow def __magic_name__ ( self : Any ) -> int: SCREAMING_SNAKE_CASE__ : Any =BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''' ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =self.default_image_processor SCREAMING_SNAKE_CASE__ : List[str] =prepare_img() SCREAMING_SNAKE_CASE__ : Any =image_processor(images=__lowercase , return_tensors='''pt''' ).pixel_values.to(__lowercase ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.ones((1, 1_96) , dtype=torch.bool ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] =model(pixel_values=__lowercase , bool_masked_pos=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : str =torch.Size((1, 1_96, 81_92) ) self.assertEqual(logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : str =torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(__lowercase ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , __lowercase , atol=1e-2 ) ) @slow def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] =BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''' ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : int =self.default_image_processor SCREAMING_SNAKE_CASE__ : int =prepare_img() SCREAMING_SNAKE_CASE__ : int =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : str =outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((1, 10_00) ) self.assertEqual(logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor([-1.2385, -1.0987, -1.0108] ).to(__lowercase ) self.assertTrue(torch.allclose(logits[0, :3] , __lowercase , atol=1e-4 ) ) SCREAMING_SNAKE_CASE__ : Any =2_81 self.assertEqual(logits.argmax(-1 ).item() , __lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ : Dict =BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =self.default_image_processor SCREAMING_SNAKE_CASE__ : int =prepare_img() SCREAMING_SNAKE_CASE__ : Optional[Any] =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : int =outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : int =torch.Size((1, 2_18_41) ) self.assertEqual(logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =torch.tensor([1.6881, -0.2787, 0.5901] ).to(__lowercase ) self.assertTrue(torch.allclose(logits[0, :3] , __lowercase , atol=1e-4 ) ) SCREAMING_SNAKE_CASE__ : List[str] =23_96 self.assertEqual(logits.argmax(-1 ).item() , __lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =BeitImageProcessor(do_resize=__lowercase , size=6_40 , do_center_crop=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) SCREAMING_SNAKE_CASE__ : int =Image.open(ds[0]['''file'''] ) SCREAMING_SNAKE_CASE__ : Any =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((1, 1_50, 1_60, 1_60) ) self.assertEqual(logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =version.parse(PIL.__version__ ) < version.parse('''9.0.0''' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE__ : int =torch.tensor( [ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], ] , device=__lowercase , ) else: SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1e-4 ) ) @slow def __magic_name__ ( self : Dict ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =model.to(__lowercase ) SCREAMING_SNAKE_CASE__ : str =BeitImageProcessor(do_resize=__lowercase , size=6_40 , do_center_crop=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) SCREAMING_SNAKE_CASE__ : List[Any] =Image.open(ds[0]['''file'''] ) SCREAMING_SNAKE_CASE__ : Optional[int] =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(5_00, 3_00)] ) SCREAMING_SNAKE_CASE__ : Any =torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =image_processor.post_process_semantic_segmentation(outputs=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Size((1_60, 1_60) ) self.assertEqual(segmentation[0].shape , __lowercase )
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } a_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = BertTokenizer def __init__( self : int , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : str=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Tuple="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : str=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : int =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Any =do_lower_case SCREAMING_SNAKE_CASE__ : Any =strip_accents SCREAMING_SNAKE_CASE__ : Dict =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Union[str, Any] =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =do_lower_case def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Union[str, Any]=None ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =[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 __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def _a( UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int =4 SCREAMING_SNAKE_CASE__ : Any =4_8 SCREAMING_SNAKE_CASE__ : List[Any] ='''pixelshuffle_aux''' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =[6, 6, 6, 6] SCREAMING_SNAKE_CASE__ : Tuple =6_0 SCREAMING_SNAKE_CASE__ : List[Any] =[6, 6, 6, 6] SCREAMING_SNAKE_CASE__ : Tuple ='''pixelshuffledirect''' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[Any] =4 SCREAMING_SNAKE_CASE__ : Any ='''nearest+conv''' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Union[str, Any] =1 SCREAMING_SNAKE_CASE__ : int =1 SCREAMING_SNAKE_CASE__ : Any =1_2_6 SCREAMING_SNAKE_CASE__ : Dict =7 SCREAMING_SNAKE_CASE__ : Optional[Any] =2_5_5.0 SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''''' return config def _a( UpperCamelCase__ : Tuple, UpperCamelCase__ : Dict ): '''simple docstring''' if "patch_embed.proj" in name and "layers" not in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''patch_embed.proj''', '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''patch_embed.norm''', '''embeddings.patch_embeddings.layernorm''' ) if "layers" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''layers''', '''encoder.stages''' ) if "residual_group.blocks" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''residual_group.blocks''', '''layers''' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''attn.proj''', '''attention.output.dense''' ) if "attn" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] =name.replace('''attn''', '''attention.self''' ) if "norm1" in name: SCREAMING_SNAKE_CASE__ : Any =name.replace('''norm1''', '''layernorm_before''' ) if "norm2" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''norm2''', '''layernorm_after''' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] =name.replace('''mlp.fc1''', '''intermediate.dense''' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ : Optional[int] =name.replace('''mlp.fc2''', '''output.dense''' ) if "q_bias" in name: SCREAMING_SNAKE_CASE__ : List[Any] =name.replace('''q_bias''', '''query.bias''' ) if "k_bias" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''k_bias''', '''key.bias''' ) if "v_bias" in name: SCREAMING_SNAKE_CASE__ : List[str] =name.replace('''v_bias''', '''value.bias''' ) if "cpb_mlp" in name: SCREAMING_SNAKE_CASE__ : int =name.replace('''cpb_mlp''', '''continuous_position_bias_mlp''' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ : Tuple =name.replace('''patch_embed.proj''', '''patch_embed.projection''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE__ : Optional[Any] ='''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE__ : Optional[int] ='''layernorm.bias''' if "conv_first" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''conv_first''', '''first_convolution''' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: SCREAMING_SNAKE_CASE__ : Any =name.replace('''conv_last''', '''final_convolution''' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''conv_before_upsample.0''', '''conv_before_upsample''' ) if "upsample.0" in name: SCREAMING_SNAKE_CASE__ : str =name.replace('''upsample.0''', '''upsample.convolution_0''' ) if "upsample.2" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] =name.replace('''upsample.2''', '''upsample.convolution_1''' ) SCREAMING_SNAKE_CASE__ : Tuple ='''upsample.''' + name elif config.upsampler == "pixelshuffledirect": SCREAMING_SNAKE_CASE__ : int =name.replace('''upsample.0.weight''', '''upsample.conv.weight''' ) SCREAMING_SNAKE_CASE__ : str =name.replace('''upsample.0.bias''', '''upsample.conv.bias''' ) else: pass else: SCREAMING_SNAKE_CASE__ : int ='''swin2sr.''' + name return name def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Tuple ): '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : List[Any] =orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] =key.split('''.''' ) SCREAMING_SNAKE_CASE__ : List[Any] =int(key_split[1] ) SCREAMING_SNAKE_CASE__ : Dict =int(key_split[4] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =config.embed_dim if "weight" in key: SCREAMING_SNAKE_CASE__ : List[Any] =val[:dim, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ : Tuple =val[-dim:, :] else: SCREAMING_SNAKE_CASE__ : str =val[:dim] SCREAMING_SNAKE_CASE__ : List[Any] =val[dim : dim * 2] SCREAMING_SNAKE_CASE__ : Dict =val[-dim:] pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =val return orig_state_dict def _a( UpperCamelCase__ : str, UpperCamelCase__ : Optional[int], UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =get_config(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =SwinaSRForImageSuperResolution(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =torch.hub.load_state_dict_from_url(UpperCamelCase__, map_location='''cpu''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =convert_state_dict(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: raise ValueError('''Missing keys when converting: {}'''.format(UpperCamelCase__ ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"Unexpected key {key} in state_dict" ) # verify values SCREAMING_SNAKE_CASE__ : Any ='''https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true''' SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open(requests.get(UpperCamelCase__, stream=UpperCamelCase__ ).raw ).convert('''RGB''' ) SCREAMING_SNAKE_CASE__ : List[Any] =SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE__ : List[Any] =1_2_6 if '''Jpeg''' in checkpoint_url else 2_5_6 SCREAMING_SNAKE_CASE__ : str =Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE__ : int =transforms(UpperCamelCase__ ).unsqueeze(0 ) if config.num_channels == 1: SCREAMING_SNAKE_CASE__ : Optional[Any] =pixel_values[:, 0, :, :].unsqueeze(1 ) SCREAMING_SNAKE_CASE__ : List[str] =model(UpperCamelCase__ ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int =torch.Size([1, 3, 5_1_2, 5_1_2] ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor( [[-0.7_0_8_7, -0.7_1_3_8, -0.6_7_2_1], [-0.8_3_4_0, -0.8_0_9_5, -0.7_2_9_8], [-0.9_1_4_9, -0.8_4_1_4, -0.7_9_4_0]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Dict =torch.tensor( [[-0.7_7_7_5, -0.8_1_0_5, -0.8_9_3_3], [-0.7_7_6_4, -0.8_3_5_6, -0.9_2_2_5], [-0.7_9_7_6, -0.8_6_8_6, -0.9_5_7_9]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here SCREAMING_SNAKE_CASE__ : Tuple =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor( [[-0.8_0_3_5, -0.7_5_0_4, -0.7_4_9_1], [-0.8_5_3_8, -0.8_1_2_4, -0.7_7_8_2], [-0.8_8_0_4, -0.8_6_5_1, -0.8_4_9_3]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] =torch.Size([1, 3, 5_1_2, 5_1_2] ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor( [[-0.7_6_6_9, -0.8_6_6_2, -0.8_7_6_7], [-0.8_8_1_0, -0.9_9_6_2, -0.9_8_2_0], [-0.9_3_4_0, -1.0_3_2_2, -1.1_1_4_9]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.tensor( [[-0.5_2_3_8, -0.5_5_5_7, -0.6_3_2_1], [-0.6_0_1_6, -0.5_9_0_3, -0.6_3_9_1], [-0.6_2_4_4, -0.6_3_3_4, -0.6_8_8_9]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3], UpperCamelCase__, atol=1e-3 ) print('''Looks ok!''' ) SCREAMING_SNAKE_CASE__ : List[str] ={ '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''': ( '''swin2SR-classical-sr-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth''': ( '''swin2SR-classical-sr-x4-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth''': ( '''swin2SR-compressed-sr-x4-48''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth''': ( '''swin2SR-lightweight-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth''': ( '''swin2SR-realworld-sr-x4-64-bsrgan-psnr''' ), } SCREAMING_SNAKE_CASE__ : int =url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(UpperCamelCase__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub(f"caidas/{model_name}" ) processor.push_to_hub(f"caidas/{model_name}" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth', type=str, help='URL of the original Swin2SR checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the converted model to the hub.') a_ = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
'''simple docstring''' import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( '''compression_format, is_archive''', [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ], ) def _a( UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : Dict, UpperCamelCase__ : Dict, UpperCamelCase__ : List[Any], UpperCamelCase__ : Dict, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Optional[int], UpperCamelCase__ : Dict, UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Dict, UpperCamelCase__ : List[str], ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any ={ '''7z''': (seven_zip_file, SevenZipExtractor), '''bz2''': (bza_file, BzipaExtractor), '''gzip''': (gz_file, GzipExtractor), '''lz4''': (lza_file, LzaExtractor), '''tar''': (tar_file, TarExtractor), '''xz''': (xz_file, XzExtractor), '''zip''': (zip_file, ZipExtractor), '''zstd''': (zstd_file, ZstdExtractor), } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =input_paths_and_base_extractors[compression_format] if input_path is None: SCREAMING_SNAKE_CASE__ : Dict =f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(UpperCamelCase__ ) assert base_extractor.is_extractable(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') base_extractor.extract(UpperCamelCase__, UpperCamelCase__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE__ : List[Any] =file_path.read_text(encoding='''utf-8''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =output_path.read_text(encoding='''utf-8''' ) SCREAMING_SNAKE_CASE__ : Dict =text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( '''compression_format, is_archive''', [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ], ) def _a( UpperCamelCase__ : Dict, UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[int], UpperCamelCase__ : int, UpperCamelCase__ : Dict, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[int], UpperCamelCase__ : Optional[int], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[str], ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any ={ '''7z''': seven_zip_file, '''bz2''': bza_file, '''gzip''': gz_file, '''lz4''': lza_file, '''tar''': tar_file, '''xz''': xz_file, '''zip''': zip_file, '''zstd''': zstd_file, } SCREAMING_SNAKE_CASE__ : Optional[int] =input_paths[compression_format] if input_path is None: SCREAMING_SNAKE_CASE__ : str =f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =Extractor.infer_extractor_format(UpperCamelCase__ ) assert extractor_format is not None SCREAMING_SNAKE_CASE__ : Tuple =tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') Extractor.extract(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE__ : str =file_path.read_text(encoding='''utf-8''' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] =output_path.read_text(encoding='''utf-8''' ) SCREAMING_SNAKE_CASE__ : int =text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.fixture def _a( UpperCamelCase__ : Tuple, UpperCamelCase__ : Any ): '''simple docstring''' import tarfile SCREAMING_SNAKE_CASE__ : Any =tmp_path / '''data_dot_dot''' directory.mkdir() SCREAMING_SNAKE_CASE__ : Union[str, Any] =directory / '''tar_file_with_dot_dot.tar''' with tarfile.TarFile(UpperCamelCase__, '''w''' ) as f: f.add(UpperCamelCase__, arcname=os.path.join('''..''', text_file.name ) ) return path @pytest.fixture def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' import tarfile SCREAMING_SNAKE_CASE__ : Optional[int] =tmp_path / '''data_sym_link''' directory.mkdir() SCREAMING_SNAKE_CASE__ : List[Any] =directory / '''tar_file_with_sym_link.tar''' os.symlink('''..''', directory / '''subdir''', target_is_directory=UpperCamelCase__ ) with tarfile.TarFile(UpperCamelCase__, '''w''' ) as f: f.add(str(directory / '''subdir''' ), arcname='''subdir''' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( '''insecure_tar_file, error_log''', [('''tar_file_with_dot_dot''', '''illegal path'''), ('''tar_file_with_sym_link''', '''Symlink''')], ) def _a( UpperCamelCase__ : str, UpperCamelCase__ : int, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Tuple, UpperCamelCase__ : Any, UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] ={ '''tar_file_with_dot_dot''': tar_file_with_dot_dot, '''tar_file_with_sym_link''': tar_file_with_sym_link, } SCREAMING_SNAKE_CASE__ : List[str] =insecure_tar_files[insecure_tar_file] SCREAMING_SNAKE_CASE__ : Tuple =tmp_path / '''extracted''' TarExtractor.extract(UpperCamelCase__, UpperCamelCase__ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict =tmpdir / '''not_a_zip_file''' # From: https://github.com/python/cpython/pull/5053 SCREAMING_SNAKE_CASE__ : Dict =( B'''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00''' B'''\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I''' B'''DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07''' B'''\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82''' ) with not_a_zip_file.open('''wb''' ) as f: f.write(UpperCamelCase__ ) assert zipfile.is_zipfile(str(UpperCamelCase__ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(UpperCamelCase__ ) # but we're right
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import collections import importlib.util import os import re from pathlib import Path a_ = 'src/transformers' # Matches is_xxx_available() a_ = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} a_ = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] a_ = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available a_ = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") a_ = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] a_ = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", a_ = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], a_ = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo a_ = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: a_ = re.compile(R'^\s*try:') # Catches a line with else: a_ = re.compile(R'^\s*else:') def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if _re_test_backend.search(UpperCamelCase__ ) is None: return None SCREAMING_SNAKE_CASE__ : Any =[b[0] for b in _re_backend.findall(UpperCamelCase__ )] backends.sort() return "_and_".join(UpperCamelCase__ ) def _a( UpperCamelCase__ : Any ): '''simple docstring''' with open(UpperCamelCase__, '''r''', encoding='''utf-8''', newline='''\n''' ) as f: SCREAMING_SNAKE_CASE__ : List[str] =f.readlines() SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while line_index < len(UpperCamelCase__ ) and not lines[line_index].startswith('''_import_structure = {''' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(UpperCamelCase__ ): return None # First grab the objects without a specific backend in _import_structure SCREAMING_SNAKE_CASE__ : Any =[] while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None: SCREAMING_SNAKE_CASE__ : List[Any] =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Dict =_re_one_line_import_struct.search(UpperCamelCase__ ).groups()[0] SCREAMING_SNAKE_CASE__ : Dict =re.findall('''\[([^\]]+)\]''', UpperCamelCase__ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] ) line_index += 1 continue SCREAMING_SNAKE_CASE__ : Optional[Any] =_re_import_struct_key_value.search(UpperCamelCase__ ) if single_line_import_search is not None: SCREAMING_SNAKE_CASE__ : Any =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(UpperCamelCase__ ) > 0] objects.extend(UpperCamelCase__ ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) line_index += 1 SCREAMING_SNAKE_CASE__ : Any ={'''none''': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('''if TYPE_CHECKING''' ): # If the line is an if not is_backend_available, we grab all objects associated. SCREAMING_SNAKE_CASE__ : List[str] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: SCREAMING_SNAKE_CASE__ : Dict =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 SCREAMING_SNAKE_CASE__ : List[Any] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =lines[line_index] if _re_import_struct_add_one.search(UpperCamelCase__ ) is not None: objects.append(_re_import_struct_add_one.search(UpperCamelCase__ ).groups()[0] ) elif _re_import_struct_add_many.search(UpperCamelCase__ ) is not None: SCREAMING_SNAKE_CASE__ : int =_re_import_struct_add_many.search(UpperCamelCase__ ).groups()[0].split(''', ''' ) SCREAMING_SNAKE_CASE__ : Dict =[obj[1:-1] for obj in imports if len(UpperCamelCase__ ) > 0] objects.extend(UpperCamelCase__ ) elif _re_between_brackets.search(UpperCamelCase__ ) is not None: SCREAMING_SNAKE_CASE__ : List[str] =_re_between_brackets.search(UpperCamelCase__ ).groups()[0].split(''', ''' ) SCREAMING_SNAKE_CASE__ : Tuple =[obj[1:-1] for obj in imports if len(UpperCamelCase__ ) > 0] objects.extend(UpperCamelCase__ ) elif _re_quote_object.search(UpperCamelCase__ ) is not None: objects.append(_re_quote_object.search(UpperCamelCase__ ).groups()[0] ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) elif line.startswith(''' ''' * 1_2 + '''"''' ): objects.append(line[1_3:-3] ) line_index += 1 SCREAMING_SNAKE_CASE__ : int =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend SCREAMING_SNAKE_CASE__ : int =[] while ( line_index < len(UpperCamelCase__ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('''else''' ) ): SCREAMING_SNAKE_CASE__ : Tuple =lines[line_index] SCREAMING_SNAKE_CASE__ : Union[str, Any] =_re_import.search(UpperCamelCase__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 SCREAMING_SNAKE_CASE__ : Any ={'''none''': objects} # Let's continue with backend-specific objects while line_index < len(UpperCamelCase__ ): # If the line is an if is_backend_available, we grab all objects associated. SCREAMING_SNAKE_CASE__ : List[str] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: SCREAMING_SNAKE_CASE__ : List[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 SCREAMING_SNAKE_CASE__ : Optional[int] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ): SCREAMING_SNAKE_CASE__ : str =lines[line_index] SCREAMING_SNAKE_CASE__ : Union[str, Any] =_re_import.search(UpperCamelCase__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 SCREAMING_SNAKE_CASE__ : Optional[Any] =objects else: line_index += 1 return import_dict_objects, type_hint_objects def _a( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Optional[int] ): '''simple docstring''' def find_duplicates(UpperCamelCase__ : Optional[int] ): return [k for k, v in collections.Counter(UpperCamelCase__ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] SCREAMING_SNAKE_CASE__ : str =[] for key in import_dict_objects.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}" ) SCREAMING_SNAKE_CASE__ : List[Any] =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): SCREAMING_SNAKE_CASE__ : Optional[int] ='''base imports''' if key == '''none''' else f"{key} backend" errors.append(f"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f" {a} in _import_structure but not in TYPE_HINT." ) return errors def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =[] for root, _, files in os.walk(UpperCamelCase__ ): if "__init__.py" in files: SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join(UpperCamelCase__, '''__init__.py''' ) SCREAMING_SNAKE_CASE__ : List[str] =parse_init(UpperCamelCase__ ) if objects is not None: SCREAMING_SNAKE_CASE__ : str =analyze_results(*UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: SCREAMING_SNAKE_CASE__ : Dict =f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append('''\n'''.join(UpperCamelCase__ ) ) if len(UpperCamelCase__ ) > 0: raise ValueError('''\n\n'''.join(UpperCamelCase__ ) ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =[] for path, directories, files in os.walk(UpperCamelCase__ ): for folder in directories: # Ignore private modules if folder.startswith('''_''' ): directories.remove(UpperCamelCase__ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(UpperCamelCase__ ) / folder).glob('''*.py''' ) ) ) == 0: continue SCREAMING_SNAKE_CASE__ : Union[str, Any] =str((Path(UpperCamelCase__ ) / folder).relative_to(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] =short_path.replace(os.path.sep, '''.''' ) submodules.append(UpperCamelCase__ ) for fname in files: if fname == "__init__.py": continue SCREAMING_SNAKE_CASE__ : List[str] =str((Path(UpperCamelCase__ ) / fname).relative_to(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : Any =short_path.replace('''.py''', '''''' ).replace(os.path.sep, '''.''' ) if len(submodule.split('''.''' ) ) == 1: submodules.append(UpperCamelCase__ ) return submodules a_ = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =importlib.util.spec_from_file_location( '''transformers''', os.path.join(UpperCamelCase__, '''__init__.py''' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =spec.loader.load_module() SCREAMING_SNAKE_CASE__ : int =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(UpperCamelCase__ ) > 0: SCREAMING_SNAKE_CASE__ : List[str] ='''\n'''.join(f"- {module}" for module in module_not_registered ) raise ValueError( '''The following submodules are not properly registered in the main init of Transformers:\n''' f"{list_of_modules}\n" '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' ) if __name__ == "__main__": check_all_inits() check_submodules()
665
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case_ = 42 # Cache store of keys snake_case_ = 42 # References of the keys in cache snake_case_ = 10 # Maximum capacity of cache def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Any =deque() SCREAMING_SNAKE_CASE__ : str =set() if not n: SCREAMING_SNAKE_CASE__ : Optional[Any] =sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =n def __magic_name__ ( self : List[str] , __lowercase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE__ : int =self.dq_store.pop() self.key_reference.remove(__lowercase ) else: self.dq_store.remove(__lowercase ) self.dq_store.appendleft(__lowercase ) self.key_reference.add(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> None: for k in self.dq_store: print(__lowercase ) def __repr__( self : List[Any] ) -> str: return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() a_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
665
1
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class __SCREAMING_SNAKE_CASE : @property def __magic_name__ ( self : str ) -> Tuple: return self.get_dummy_input() @property def __magic_name__ ( self : int ) -> List[Any]: if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'." ) def __magic_name__ ( self : str , __lowercase : Any=True , __lowercase : Any=False , __lowercase : List[Any]=False , __lowercase : Dict=False , ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =4 SCREAMING_SNAKE_CASE__ : Tuple =32 SCREAMING_SNAKE_CASE__ : Optional[int] =(32, 32) SCREAMING_SNAKE_CASE__ : str =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.device(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =(batch_size, num_channels) + sizes SCREAMING_SNAKE_CASE__ : Any =randn_tensor(__lowercase , generator=__lowercase , device=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] ={'''hidden_states''': hidden_states} if include_temb: SCREAMING_SNAKE_CASE__ : Any =1_28 SCREAMING_SNAKE_CASE__ : List[Any] =randn_tensor((batch_size, temb_channels) , generator=__lowercase , device=__lowercase ) if include_res_hidden_states_tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =torch.manual_seed(1 ) SCREAMING_SNAKE_CASE__ : Tuple =(randn_tensor(__lowercase , generator=__lowercase , device=__lowercase ),) if include_encoder_hidden_states: SCREAMING_SNAKE_CASE__ : Dict =floats_tensor((batch_size, 32, 32) ).to(__lowercase ) if include_skip_sample: SCREAMING_SNAKE_CASE__ : str =randn_tensor(((batch_size, 3) + sizes) , generator=__lowercase , device=__lowercase ) return dummy_input def __magic_name__ ( self : int ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int ={ '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 1_28, } if self.block_type == "up": SCREAMING_SNAKE_CASE__ : str =32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.dummy_input return init_dict, inputs_dict def __magic_name__ ( self : int , __lowercase : Union[str, Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict =self.block_class(**__lowercase ) unet_block.to(__lowercase ) unet_block.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =unet_block(**__lowercase ) if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[int] =output[0] self.assertEqual(output.shape , self.output_shape ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =output[0, -1, -3:, -3:] SCREAMING_SNAKE_CASE__ : int =torch.tensor(__lowercase ).to(__lowercase ) assert torch_all_close(output_slice.flatten() , __lowercase , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str =self.block_class(**__lowercase ) model.to(__lowercase ) model.train() SCREAMING_SNAKE_CASE__ : str =model(**__lowercase ) if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Tuple =output[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.device(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =randn_tensor(output.shape , device=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.nn.functional.mse_loss(__lowercase , __lowercase ) loss.backward()
665
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor a_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Tuple , *__lowercase : Dict , **__lowercase : Dict ) -> None: warnings.warn( '''The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DonutImageProcessor instead.''' , __lowercase , ) super().__init__(*__lowercase , **__lowercase )
665
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def __magic_name__ ( self : int ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] =TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) SCREAMING_SNAKE_CASE__ : Any ={ '''input_ids''': tf.convert_to_tensor([[0, 26_46, 1_02_69, 83, 9_99_42, 2]] , dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase )['''last_hidden_state'''] SCREAMING_SNAKE_CASE__ : Tuple =tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , __lowercase ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Union[str, Any] =tf.convert_to_tensor( [ [ [0.0681762, 0.10894451, 0.06772504], [-0.06423668, 0.02366615, 0.04329344], [-0.06057295, 0.09974135, -0.00070584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : list ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =len(UpperCamelCase__ ) for _ in range(UpperCamelCase__ ): for i in range(_ % 2, arr_size - 1, 2 ): if arr[i + 1] < arr[i]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =arr[i + 1], arr[i] return arr if __name__ == "__main__": a_ = list(range(1_0, 0, -1)) print(F'''Original: {arr}. Sorted: {odd_even_transposition(arr)}''')
665
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
1
'''simple docstring''' import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params a_ = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def _a( UpperCamelCase__ : Dict ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: SCREAMING_SNAKE_CASE__ : Optional[Any] =k.replace(UpperCamelCase__, UpperCamelCase__ ) return k def _a( UpperCamelCase__ : dict, UpperCamelCase__ : dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =PegasusConfig(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int =PegasusForConditionalGeneration(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =torch_model.model.state_dict() SCREAMING_SNAKE_CASE__ : List[Any] ={} for k, v in tf_weights.items(): SCREAMING_SNAKE_CASE__ : Dict =rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(f"could not find new key {new_k} in state dict. (converted from {k})" ) if "dense" in k or "proj" in new_k: SCREAMING_SNAKE_CASE__ : Union[str, Any] =v.T SCREAMING_SNAKE_CASE__ : Any =torch.tensor(UpperCamelCase__, dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, f"{new_k}, {k}, {v.shape}, {sd[new_k].shape}" # make sure embedding.padding_idx is respected SCREAMING_SNAKE_CASE__ : Dict =torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =mapping['''shared.weight'''] SCREAMING_SNAKE_CASE__ : Dict =mapping['''shared.weight'''] SCREAMING_SNAKE_CASE__ : Tuple ={k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith('''bias''' ) and k not in mapping} mapping.update(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =torch_model.model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =[ k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight'''] ] assert unexpected_missing == [], f"no matches found for the following torch keys {unexpected_missing}" assert extra == [], f"no matches found for the following tf keys {extra}" return torch_model def _a( UpperCamelCase__ : Dict="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =tf.train.list_variables(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str ={} SCREAMING_SNAKE_CASE__ : List[Any] =['''Adafactor''', '''global_step'''] for name, shape in tqdm(UpperCamelCase__, desc='''converting tf checkpoint to dict''' ): SCREAMING_SNAKE_CASE__ : List[str] =any(pat in name for pat in ignore_name ) if skip_key: continue SCREAMING_SNAKE_CASE__ : Tuple =tf.train.load_variable(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =array return tf_weights def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =Path(UpperCamelCase__ ).parent.name SCREAMING_SNAKE_CASE__ : Dict =task_specific_params[f"summarization_{dataset}"]['''max_position_embeddings'''] SCREAMING_SNAKE_CASE__ : Tuple =PegasusTokenizer.from_pretrained('''sshleifer/pegasus''', model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model SCREAMING_SNAKE_CASE__ : int =get_tf_weights_as_numpy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =task_specific_params[f"summarization_{dataset}"] if dataset == "large": SCREAMING_SNAKE_CASE__ : Dict =task_specific_params SCREAMING_SNAKE_CASE__ : List[str] =convert_pegasus(UpperCamelCase__, UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''' ) sd.pop('''model.encoder.embed_positions.weight''' ) torch.save(UpperCamelCase__, Path(UpperCamelCase__ ) / '''pytorch_model.bin''' ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') a_ = parser.parse_args() if args.save_dir is None: a_ = Path(args.tf_ckpt_path).parent.name a_ = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart a_ = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } a_ = { 'facebook/bart-base': 1_0_2_4, 'facebook/bart-large': 1_0_2_4, 'facebook/bart-large-mnli': 1_0_2_4, 'facebook/bart-large-cnn': 1_0_2_4, 'facebook/bart-large-xsum': 1_0_2_4, 'yjernite/bart_eli5': 1_0_2_4, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): 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_ = BartTokenizer def __init__( self : int , __lowercase : Tuple=None , __lowercase : int=None , __lowercase : Any=None , __lowercase : Tuple="replace" , __lowercase : str="<s>" , __lowercase : int="</s>" , __lowercase : Optional[int]="</s>" , __lowercase : Optional[Any]="<s>" , __lowercase : Dict="<unk>" , __lowercase : List[Any]="<pad>" , __lowercase : Any="<mask>" , __lowercase : Optional[int]=False , __lowercase : Any=True , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , __lowercase , tokenizer_file=__lowercase , errors=__lowercase , bos_token=__lowercase , eos_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , unk_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , add_prefix_space=__lowercase , trim_offsets=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : Optional[int] =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __lowercase ) != add_prefix_space: SCREAMING_SNAKE_CASE__ : str =getattr(__lowercase , pre_tok_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =add_prefix_space SCREAMING_SNAKE_CASE__ : List[str] =pre_tok_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE__ : Optional[Any] ='''post_processor''' SCREAMING_SNAKE_CASE__ : List[Any] =getattr(self.backend_tokenizer , __lowercase , __lowercase ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ : List[Any] =json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE__ : str =tuple(state['''sep'''] ) if "cls" in state: SCREAMING_SNAKE_CASE__ : str =tuple(state['''cls'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =False if state.get('''add_prefix_space''' , __lowercase ) != add_prefix_space: SCREAMING_SNAKE_CASE__ : Union[str, Any] =add_prefix_space SCREAMING_SNAKE_CASE__ : Tuple =True if state.get('''trim_offsets''' , __lowercase ) != trim_offsets: SCREAMING_SNAKE_CASE__ : Optional[Any] =trim_offsets SCREAMING_SNAKE_CASE__ : str =True if changes_to_apply: SCREAMING_SNAKE_CASE__ : Tuple =getattr(__lowercase , state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Tuple =component_class(**__lowercase ) setattr(self.backend_tokenizer , __lowercase , __lowercase ) @property def __magic_name__ ( self : str ) -> str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __magic_name__ ( self : str , __lowercase : List[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else value SCREAMING_SNAKE_CASE__ : Union[str, Any] =value def __magic_name__ ( self : str , *__lowercase : int , **__lowercase : str ) -> BatchEncoding: SCREAMING_SNAKE_CASE__ : Tuple =kwargs.get('''is_split_into_words''' , __lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*__lowercase , **__lowercase ) def __magic_name__ ( self : Optional[int] , *__lowercase : Union[str, Any] , **__lowercase : Optional[int] ) -> BatchEncoding: SCREAMING_SNAKE_CASE__ : Any =kwargs.get('''is_split_into_words''' , __lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*__lowercase , **__lowercase ) def __magic_name__ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase ) def __magic_name__ ( self : Tuple , __lowercase : List[Any] , __lowercase : List[str]=None ) -> List[str]: SCREAMING_SNAKE_CASE__ : str =[self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : int =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
665
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
1
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int a_ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ): snake_case_ = None def _a( UpperCamelCase__ : "pyspark.sql.DataFrame", UpperCamelCase__ : List[int], ): '''simple docstring''' import pyspark def generate_fn(): SCREAMING_SNAKE_CASE__ : str =df.select('''*''', pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: SCREAMING_SNAKE_CASE__ : List[str] =df_with_partition_id.select('''*''' ).where(f"part_id = {partition_id}" ).drop('''part_id''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =partition_df.collect() SCREAMING_SNAKE_CASE__ : Any =0 for row in rows: yield f"{partition_id}_{row_id}", row.asDict() row_id += 1 return generate_fn class __SCREAMING_SNAKE_CASE ( _BaseExamplesIterable ): def __init__( self : Optional[Any] , __lowercase : "pyspark.sql.DataFrame" , __lowercase : Optional[int]=None , ) -> Dict: SCREAMING_SNAKE_CASE__ : str =df SCREAMING_SNAKE_CASE__ : List[Any] =partition_order or range(self.df.rdd.getNumPartitions() ) SCREAMING_SNAKE_CASE__ : List[str] =_generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Optional[int] ) -> Tuple: yield from self.generate_examples_fn() def __magic_name__ ( self : str , __lowercase : np.random.Generator ) -> "SparkExamplesIterable": SCREAMING_SNAKE_CASE__ : str =list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__lowercase ) return SparkExamplesIterable(self.df , partition_order=__lowercase ) def __magic_name__ ( self : str , __lowercase : int , __lowercase : int ) -> "SparkExamplesIterable": SCREAMING_SNAKE_CASE__ : List[str] =self.split_shard_indices_by_worker(__lowercase , __lowercase ) return SparkExamplesIterable(self.df , partition_order=__lowercase ) @property def __magic_name__ ( self : int ) -> int: return len(self.partition_order ) class __SCREAMING_SNAKE_CASE ( datasets.DatasetBuilder ): snake_case_ = SparkConfig def __init__( self : Tuple , __lowercase : "pyspark.sql.DataFrame" , __lowercase : str = None , __lowercase : str = None , **__lowercase : List[str] , ) -> Dict: import pyspark SCREAMING_SNAKE_CASE__ : Union[str, Any] =pyspark.sql.SparkSession.builder.getOrCreate() SCREAMING_SNAKE_CASE__ : List[Any] =df SCREAMING_SNAKE_CASE__ : Dict =working_dir super().__init__( cache_dir=__lowercase , config_name=str(self.df.semanticHash() ) , **__lowercase , ) def __magic_name__ ( self : Tuple ) -> List[Any]: # Returns the path of the created file. def create_cache_and_write_probe(__lowercase : Any ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join(self._cache_dir , '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__lowercase , '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''' , '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: SCREAMING_SNAKE_CASE__ : List[str] =( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__lowercase ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def __magic_name__ ( self : Optional[Any] ) -> Dict: return datasets.DatasetInfo(features=self.config.features ) def __magic_name__ ( self : str , __lowercase : datasets.download.download_manager.DownloadManager ) -> List[str]: return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __magic_name__ ( self : Any , __lowercase : Any ) -> Tuple: import pyspark def get_arrow_batch_size(__lowercase : str ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.df.count() SCREAMING_SNAKE_CASE__ : Optional[Any] =df_num_rows if df_num_rows <= 1_00 else 1_00 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. SCREAMING_SNAKE_CASE__ : List[Any] =( self.df.limit(__lowercase ) .repartition(1 ) .mapInArrow(__lowercase , '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) SCREAMING_SNAKE_CASE__ : Optional[int] =approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. SCREAMING_SNAKE_CASE__ : int =min(__lowercase , int(approx_total_size / max_shard_size ) ) SCREAMING_SNAKE_CASE__ : Tuple =self.df.repartition(__lowercase ) def __magic_name__ ( self : Dict , __lowercase : str , __lowercase : str , __lowercase : int , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark SCREAMING_SNAKE_CASE__ : str =ParquetWriter if file_format == '''parquet''' else ArrowWriter SCREAMING_SNAKE_CASE__ : Tuple =os.path.join(self._working_dir , os.path.basename(__lowercase ) ) if self._working_dir else fpath SCREAMING_SNAKE_CASE__ : Optional[int] =file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. SCREAMING_SNAKE_CASE__ : Any =self.config.features SCREAMING_SNAKE_CASE__ : Any =self._writer_batch_size SCREAMING_SNAKE_CASE__ : Tuple =self._fs.storage_options def write_arrow(__lowercase : Optional[Any] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. SCREAMING_SNAKE_CASE__ : List[Any] =pyspark.TaskContext().taskAttemptId() SCREAMING_SNAKE_CASE__ : int =next(__lowercase , __lowercase ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 SCREAMING_SNAKE_CASE__ : Optional[int] =writer_class( features=__lowercase , path=working_fpath.replace('''SSSSS''' , F"{shard_id:05d}" ).replace('''TTTTT''' , F"{task_id:05d}" ) , writer_batch_size=__lowercase , storage_options=__lowercase , embed_local_files=__lowercase , ) SCREAMING_SNAKE_CASE__ : List[Any] =pa.Table.from_batches([first_batch] ) writer.write_table(__lowercase ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) shard_id += 1 SCREAMING_SNAKE_CASE__ : List[Any] =writer_class( features=writer._features , path=working_fpath.replace('''SSSSS''' , F"{shard_id:05d}" ).replace('''TTTTT''' , F"{task_id:05d}" ) , writer_batch_size=__lowercase , storage_options=__lowercase , embed_local_files=__lowercase , ) SCREAMING_SNAKE_CASE__ : str =pa.Table.from_batches([batch] ) writer.write_table(__lowercase ) if writer._num_bytes > 0: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__lowercase ) ): SCREAMING_SNAKE_CASE__ : str =os.path.join(os.path.dirname(__lowercase ) , os.path.basename(__lowercase ) ) shutil.move(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.df.mapInArrow(__lowercase , '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ) , pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ) , pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ) , pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __magic_name__ ( self : Union[str, Any] , __lowercase : "datasets.SplitGenerator" , __lowercase : str = "arrow" , __lowercase : Optional[Union[str, int]] = None , __lowercase : Optional[int] = None , **__lowercase : str , ) -> Any: self._validate_cache_dir() SCREAMING_SNAKE_CASE__ : Any =convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =not is_remote_filesystem(self._fs ) SCREAMING_SNAKE_CASE__ : Optional[int] =os.path.join if is_local else posixpath.join SCREAMING_SNAKE_CASE__ : Dict ='''-TTTTT-SSSSS-of-NNNNN''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =F"{self.name}-{split_generator.name}{SUFFIX}.{file_format}" SCREAMING_SNAKE_CASE__ : Optional[Any] =path_join(self._output_dir , __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =0 SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : List[Any] =0 SCREAMING_SNAKE_CASE__ : Dict =[] SCREAMING_SNAKE_CASE__ : Tuple =[] for task_id, content in self._prepare_split_single(__lowercase , __lowercase , __lowercase ): ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Any =content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =total_num_examples SCREAMING_SNAKE_CASE__ : List[Any] =total_num_bytes # should rename everything at the end logger.debug(F"Renaming {total_shards} shards." ) if total_shards > 1: SCREAMING_SNAKE_CASE__ : Dict =all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. SCREAMING_SNAKE_CASE__ : str =self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __lowercase : int , __lowercase : int , __lowercase : int , ): rename( __lowercase , fpath.replace('''SSSSS''' , F"{shard_id:05d}" ).replace('''TTTTT''' , F"{task_id:05d}" ) , fpath.replace('''TTTTT-SSSSS''' , F"{global_shard_id:05d}" ).replace('''NNNNN''' , F"{total_shards:05d}" ) , ) SCREAMING_SNAKE_CASE__ : Dict =[] SCREAMING_SNAKE_CASE__ : Dict =0 for i in range(len(__lowercase ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =task_id_and_num_shards[i] for shard_id in range(__lowercase ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__lowercase , len(__lowercase ) ).map(lambda __lowercase : _rename_shard(*__lowercase ) ).collect() else: # don't use any pattern SCREAMING_SNAKE_CASE__ : Optional[Any] =0 SCREAMING_SNAKE_CASE__ : Optional[Any] =task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''' , F"{shard_id:05d}" ).replace('''TTTTT''' , F"{task_id:05d}" ) , fpath.replace(__lowercase , '''''' ) , ) def __magic_name__ ( self : Union[str, Any] , __lowercase : "datasets.SplitGenerator" , ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df )
665
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _a( UpperCamelCase__ : str, UpperCamelCase__ : Tuple, UpperCamelCase__ : Any, UpperCamelCase__ : List[str], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase__ ) as metadata_file: SCREAMING_SNAKE_CASE__ : Optional[int] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =LukeConfig(use_entity_aware_attention=UpperCamelCase__, **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(UpperCamelCase__, map_location='''cpu''' )['''module'''] # Load the entity vocab file SCREAMING_SNAKE_CASE__ : List[str] =load_original_entity_vocab(UpperCamelCase__ ) # add an entry for [MASK2] SCREAMING_SNAKE_CASE__ : Optional[int] =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 SCREAMING_SNAKE_CASE__ : Optional[int] =XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken('''<ent>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =AddedToken('''<ent2>''', lstrip=UpperCamelCase__, rstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] =json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int ='''MLukeTokenizer''' with open(os.path.join(UpperCamelCase__, '''tokenizer_config.json''' ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__, MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ), '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE__ : str =tokenizer.convert_tokens_to_ids(['''@'''] )[0] SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.convert_tokens_to_ids(['''#'''] )[0] SCREAMING_SNAKE_CASE__ : Dict =state_dict['''embeddings.word_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : List[str] =word_emb[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Tuple =word_emb[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[bias_name] SCREAMING_SNAKE_CASE__ : List[Any] =decoder_bias[ent_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : str =decoder_bias[enta_init_index].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE__ : Tuple =f"encoder.layer.{layer_index}.attention.self." SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ : List[Any] =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE__ : Any =state_dict['''entity_embeddings.entity_embeddings.weight'''] SCREAMING_SNAKE_CASE__ : Any =entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' SCREAMING_SNAKE_CASE__ : Optional[int] =state_dict['''entity_predictions.bias'''] SCREAMING_SNAKE_CASE__ : Tuple =entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any =torch.cat([entity_prediction_bias, entity_mask_bias] ) SCREAMING_SNAKE_CASE__ : int =LukeForMaskedLM(config=UpperCamelCase__ ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) SCREAMING_SNAKE_CASE__ : Tuple =OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): SCREAMING_SNAKE_CASE__ : Optional[Any] =state_dict[key] else: SCREAMING_SNAKE_CASE__ : Any =state_dict[key] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =model.load_state_dict(UpperCamelCase__, strict=UpperCamelCase__ ) if set(UpperCamelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(f"Unexpected unexpected_keys: {unexpected_keys}" ) if set(UpperCamelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs SCREAMING_SNAKE_CASE__ : Any =MLukeTokenizer.from_pretrained(UpperCamelCase__, task='''entity_classification''' ) SCREAMING_SNAKE_CASE__ : str ='''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =(0, 9) SCREAMING_SNAKE_CASE__ : str =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[Any] =model(**UpperCamelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : str =torch.Size((1, 3_3, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base SCREAMING_SNAKE_CASE__ : Any =torch.Size((1, 1, 7_6_8) ) SCREAMING_SNAKE_CASE__ : int =torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" f" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], UpperCamelCase__, atol=1e-4 ): raise ValueError # Verify masked word/entity prediction SCREAMING_SNAKE_CASE__ : str =MLukeTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''Tokyo is the capital of <mask>.''' SCREAMING_SNAKE_CASE__ : Dict =(2_4, 3_0) SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer(UpperCamelCase__, entity_spans=[span], return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__ : List[str] =model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =encoding['''input_ids'''][0].tolist() SCREAMING_SNAKE_CASE__ : Any =input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.entity_logits[0][0].argmax().item() SCREAMING_SNAKE_CASE__ : Dict =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(UpperCamelCase__ ) ) model.save_pretrained(UpperCamelCase__ ) def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =['''[MASK]''', '''[PAD]''', '''[UNK]'''] SCREAMING_SNAKE_CASE__ : List[str] =[json.loads(UpperCamelCase__ ) for line in open(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Optional[int] ={} for entry in data: SCREAMING_SNAKE_CASE__ : Tuple =entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: SCREAMING_SNAKE_CASE__ : str =entity_id break SCREAMING_SNAKE_CASE__ : Union[str, Any] =f"{language}:{entity_name}" SCREAMING_SNAKE_CASE__ : Union[str, Any] =entity_id return new_mapping if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a_ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
665
1
'''simple docstring''' import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 a_ = 0B1011_0011_1110_1100_1001_0000_0111_1011_1011_0001_1001_1110 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 a_ = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class __SCREAMING_SNAKE_CASE : def __init__( self : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =WATERMARK_BITS SCREAMING_SNAKE_CASE__ : Tuple =WatermarkEncoder() self.encoder.set_watermark('''bits''' , self.watermark ) def __magic_name__ ( self : Tuple , __lowercase : torch.FloatTensor ) -> int: # can't encode images that are smaller than 256 if images.shape[-1] < 2_56: return images SCREAMING_SNAKE_CASE__ : str =(2_55 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE__ : Union[str, Any] =[self.encoder.encode(__lowercase , '''dwtDct''' ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[int] =torch.from_numpy(np.array(__lowercase ) ).permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.clamp(2 * (images / 2_55 - 0.5) , min=-1.0 , max=1.0 ) return images
665
'''simple docstring''' def _a( UpperCamelCase__ : str, UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : List[Any] =True for i in range(UpperCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE__ : Optional[int] =True if a[i].islower(): SCREAMING_SNAKE_CASE__ : List[Any] =True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from collections.abc import Iterable from typing import Generic, TypeVar a_ = TypeVar('_T') class __SCREAMING_SNAKE_CASE ( Generic[_T] ): def __init__( self : List[Any] , __lowercase : Iterable[_T] | None = None ) -> None: SCREAMING_SNAKE_CASE__ : list[_T] =list(iterable or [] ) SCREAMING_SNAKE_CASE__ : list[_T] =[] def __len__( self : List[str] ) -> int: return len(self._stacka ) + len(self._stacka ) def __repr__( self : List[str] ) -> str: return F"Queue({tuple(self._stacka[::-1] + self._stacka )})" def __magic_name__ ( self : List[Any] , __lowercase : _T ) -> None: self._stacka.append(__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> _T: SCREAMING_SNAKE_CASE__ : List[str] =self._stacka.pop SCREAMING_SNAKE_CASE__ : List[Any] =self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError('''Queue is empty''' ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
665
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[Any] , __lowercase : List[str]=13 , __lowercase : int=7 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : List[Any]=True , __lowercase : str=True , __lowercase : Tuple=99 , __lowercase : Union[str, Any]=64 , __lowercase : Tuple=32 , __lowercase : Optional[Any]=5 , __lowercase : Tuple=4 , __lowercase : Optional[int]=37 , __lowercase : int="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : List[Any]=0.1 , __lowercase : List[Any]=5_12 , __lowercase : int=16 , __lowercase : Optional[int]=2 , __lowercase : Tuple=0.02 , __lowercase : List[str]=3 , __lowercase : List[str]=4 , __lowercase : List[str]=None , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Any =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =seq_length SCREAMING_SNAKE_CASE__ : Dict =is_training SCREAMING_SNAKE_CASE__ : List[Any] =use_input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] =use_labels SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : str =hidden_size SCREAMING_SNAKE_CASE__ : Any =embedding_size SCREAMING_SNAKE_CASE__ : Tuple =num_hidden_layers SCREAMING_SNAKE_CASE__ : str =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any =max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : Any =type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE__ : str =num_labels SCREAMING_SNAKE_CASE__ : List[str] =num_choices SCREAMING_SNAKE_CASE__ : List[str] =scope def __magic_name__ ( self : str ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int =None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : int =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =None SCREAMING_SNAKE_CASE__ : Optional[Any] =None SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : List[str] ) -> Any: return MegatronBertConfig( 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 , embedding_size=self.embedding_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=__lowercase , initializer_range=self.initializer_range , ) def __magic_name__ ( self : Any , __lowercase : Tuple , __lowercase : Any , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =model(__lowercase , token_type_ids=__lowercase ) SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ ( self : Dict , __lowercase : Optional[int] , __lowercase : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : Any , __lowercase : Optional[int] , __lowercase : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =MegatronBertForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : List[str] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : str , __lowercase : Any , __lowercase : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =MegatronBertForNextSentencePrediction(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : List[str] , __lowercase : Optional[int] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =MegatronBertForPreTraining(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , next_sentence_label=__lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __magic_name__ ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Any , __lowercase : Any , __lowercase : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =MegatronBertForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __magic_name__ ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : int , __lowercase : List[str] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.num_labels SCREAMING_SNAKE_CASE__ : Dict =MegatronBertForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : Any , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple =self.num_labels SCREAMING_SNAKE_CASE__ : int =MegatronBertForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : Dict , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Any , __lowercase : List[Any] , __lowercase : int , __lowercase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.num_choices SCREAMING_SNAKE_CASE__ : List[str] =MegatronBertForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[int] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : str ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) snake_case_ = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True # test_resize_embeddings = False snake_case_ = False def __magic_name__ ( self : List[Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : Tuple=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str ) -> Dict: self.config_tester.run_common_tests() def __magic_name__ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowercase ) def __magic_name__ ( self : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowercase ) def __magic_name__ ( self : Dict ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowercase ) def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' return torch.tensor( UpperCamelCase__, dtype=torch.long, device=UpperCamelCase__, ) a_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow @unittest.skip('''Model is not available.''' ) def __magic_name__ ( self : Any ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any ='''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ : Optional[int] =os.path.join(os.environ['''MYDIR'''] , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =MegatronBertModel.from_pretrained(__lowercase ) model.to(__lowercase ) model.half() SCREAMING_SNAKE_CASE__ : Dict =_long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase )[0] SCREAMING_SNAKE_CASE__ : Dict =torch.Size((1, 9, 10_24) ) self.assertEqual(output.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : str =[-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ : List[Any] =output[0, ii, jj] SCREAMING_SNAKE_CASE__ : Tuple =expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ : List[str] ='''ii={} jj={} a={} b={}'''.format(__lowercase , __lowercase , __lowercase , __lowercase ) self.assertTrue(math.isclose(__lowercase , __lowercase , rel_tol=__lowercase , abs_tol=__lowercase ) , msg=__lowercase )
665
1
'''simple docstring''' 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, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = 42 @flax_register_to_config class __SCREAMING_SNAKE_CASE ( nn.Module , lowerCamelCase , lowerCamelCase ): snake_case_ = 32 snake_case_ = 4 snake_case_ = 4 snake_case_ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) snake_case_ = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") snake_case_ = False snake_case_ = (320, 640, 1280, 1280) snake_case_ = 2 snake_case_ = 8 snake_case_ = None snake_case_ = 1280 snake_case_ = 0.0 snake_case_ = False snake_case_ = jnp.floataa snake_case_ = True snake_case_ = 0 snake_case_ = False def __magic_name__ ( self : List[Any] , __lowercase : jax.random.KeyArray ) -> FrozenDict: # init input tensors SCREAMING_SNAKE_CASE__ : int =(1, self.in_channels, self.sample_size, self.sample_size) SCREAMING_SNAKE_CASE__ : List[Any] =jnp.zeros(__lowercase , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : int =jnp.ones((1,) , dtype=jnp.intaa ) SCREAMING_SNAKE_CASE__ : List[Any] =jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =jax.random.split(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] ={'''params''': params_rng, '''dropout''': dropout_rng} return self.init(__lowercase , __lowercase , __lowercase , __lowercase )["params"] def __magic_name__ ( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int =self.block_out_channels SCREAMING_SNAKE_CASE__ : Optional[Any] =block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( '''At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.''' ) # 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. SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.num_attention_heads or self.attention_head_dim # input SCREAMING_SNAKE_CASE__ : Tuple =nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time SCREAMING_SNAKE_CASE__ : Optional[int] =FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) SCREAMING_SNAKE_CASE__ : Optional[int] =FlaxTimestepEmbedding(__lowercase , dtype=self.dtype ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.only_cross_attention if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : List[Any] =(only_cross_attention,) * len(self.down_block_types ) if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Any =(num_attention_heads,) * len(self.down_block_types ) # down SCREAMING_SNAKE_CASE__ : Union[str, Any] =[] SCREAMING_SNAKE_CASE__ : Optional[Any] =block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): SCREAMING_SNAKE_CASE__ : List[str] =output_channel SCREAMING_SNAKE_CASE__ : Tuple =block_out_channels[i] SCREAMING_SNAKE_CASE__ : Optional[int] =i == len(__lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": SCREAMING_SNAKE_CASE__ : Tuple =FlaxCrossAttnDownBlockaD( in_channels=__lowercase , out_channels=__lowercase , 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] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: SCREAMING_SNAKE_CASE__ : str =FlaxDownBlockaD( in_channels=__lowercase , out_channels=__lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__lowercase ) SCREAMING_SNAKE_CASE__ : int =down_blocks # mid SCREAMING_SNAKE_CASE__ : List[Any] =FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up SCREAMING_SNAKE_CASE__ : int =[] SCREAMING_SNAKE_CASE__ : Any =list(reversed(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =list(reversed(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Dict =list(reversed(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): SCREAMING_SNAKE_CASE__ : Optional[int] =output_channel SCREAMING_SNAKE_CASE__ : List[Any] =reversed_block_out_channels[i] SCREAMING_SNAKE_CASE__ : List[Any] =reversed_block_out_channels[min(i + 1 , len(__lowercase ) - 1 )] SCREAMING_SNAKE_CASE__ : Optional[int] =i == len(__lowercase ) - 1 if up_block_type == "CrossAttnUpBlock2D": SCREAMING_SNAKE_CASE__ : List[Any] =FlaxCrossAttnUpBlockaD( in_channels=__lowercase , out_channels=__lowercase , prev_output_channel=__lowercase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: SCREAMING_SNAKE_CASE__ : List[Any] =FlaxUpBlockaD( in_channels=__lowercase , out_channels=__lowercase , prev_output_channel=__lowercase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =output_channel SCREAMING_SNAKE_CASE__ : Optional[Any] =up_blocks # out SCREAMING_SNAKE_CASE__ : Optional[int] =nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) SCREAMING_SNAKE_CASE__ : str =nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Union[str, Any] , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : str , __lowercase : Union[str, Any]=None , __lowercase : List[str]=None , __lowercase : bool = True , __lowercase : bool = False , ) -> Union[FlaxUNetaDConditionOutput, Tuple]: # 1. time if not isinstance(__lowercase , jnp.ndarray ): SCREAMING_SNAKE_CASE__ : List[Any] =jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =timesteps.astype(dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] =jnp.expand_dims(__lowercase , 0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.time_proj(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =self.time_embedding(__lowercase ) # 2. pre-process SCREAMING_SNAKE_CASE__ : str =jnp.transpose(__lowercase , (0, 2, 3, 1) ) SCREAMING_SNAKE_CASE__ : Tuple =self.conv_in(__lowercase ) # 3. down SCREAMING_SNAKE_CASE__ : Tuple =(sample,) for down_block in self.down_blocks: if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =down_block(__lowercase , __lowercase , __lowercase , deterministic=not train ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =down_block(__lowercase , __lowercase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: SCREAMING_SNAKE_CASE__ : int =() for down_block_res_sample, down_block_additional_residual in zip( __lowercase , __lowercase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) SCREAMING_SNAKE_CASE__ : Dict =new_down_block_res_samples # 4. mid SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.mid_block(__lowercase , __lowercase , __lowercase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ : List[str] =down_block_res_samples[-(self.layers_per_block + 1) :] SCREAMING_SNAKE_CASE__ : Optional[Any] =down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[int] =up_block( __lowercase , temb=__lowercase , encoder_hidden_states=__lowercase , res_hidden_states_tuple=__lowercase , deterministic=not train , ) else: SCREAMING_SNAKE_CASE__ : int =up_block(__lowercase , temb=__lowercase , res_hidden_states_tuple=__lowercase , deterministic=not train ) # 6. post-process SCREAMING_SNAKE_CASE__ : List[Any] =self.conv_norm_out(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =nn.silu(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.conv_out(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =jnp.transpose(__lowercase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=__lowercase )
665
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __magic_name__ ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() SCREAMING_SNAKE_CASE__ : List[str] =[sys.executable] + distributed_args execute_subprocess_async(__lowercase , env=os.environ.copy() )
665
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): def __init__( self : str , __lowercase : list[T] , __lowercase : Callable[[T, T], T] ) -> None: SCREAMING_SNAKE_CASE__ : Any | T =None SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) SCREAMING_SNAKE_CASE__ : list[T] =[any_type for _ in range(self.N )] + arr SCREAMING_SNAKE_CASE__ : List[Any] =fnc self.build() def __magic_name__ ( self : List[Any] ) -> None: for p in range(self.N - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE__ : Any =self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : T ) -> None: p += self.N SCREAMING_SNAKE_CASE__ : Dict =v while p > 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] =p // 2 SCREAMING_SNAKE_CASE__ : int =self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> T | None: # noqa: E741 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =l + self.N, r + self.N SCREAMING_SNAKE_CASE__ : T | None =None while l <= r: if l % 2 == 1: SCREAMING_SNAKE_CASE__ : Tuple =self.st[l] if res is None else self.fn(__lowercase , self.st[l] ) if r % 2 == 0: SCREAMING_SNAKE_CASE__ : List[Any] =self.st[r] if res is None else self.fn(__lowercase , self.st[r] ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =(l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce a_ = [1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] a_ = { 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } a_ = SegmentTree(test_array, min) a_ = SegmentTree(test_array, max) a_ = SegmentTree(test_array, lambda a, b: a + b) def _a( ): '''simple docstring''' for i in range(len(UpperCamelCase__ ) ): for j in range(UpperCamelCase__, len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : Optional[int] =reduce(UpperCamelCase__, test_array[i : j + 1] ) SCREAMING_SNAKE_CASE__ : Optional[Any] =reduce(UpperCamelCase__, test_array[i : j + 1] ) SCREAMING_SNAKE_CASE__ : Any =reduce(lambda UpperCamelCase__, UpperCamelCase__ : a + b, test_array[i : j + 1] ) assert min_range == min_segment_tree.query(UpperCamelCase__, UpperCamelCase__ ) assert max_range == max_segment_tree.query(UpperCamelCase__, UpperCamelCase__ ) assert sum_range == sum_segment_tree.query(UpperCamelCase__, UpperCamelCase__ ) test_all_segments() for index, value in test_updates.items(): a_ = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = ShapEImgaImgPipeline snake_case_ = ["""image"""] snake_case_ = ["""image"""] snake_case_ = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[Any] ) -> List[Any]: return 32 @property def __magic_name__ ( self : List[str] ) -> Optional[int]: return 32 @property def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: return self.time_input_dim * 4 @property def __magic_name__ ( self : Dict ) -> Union[str, Any]: return 8 @property def __magic_name__ ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) SCREAMING_SNAKE_CASE__ : str =CLIPVisionModel(__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : int =CLIPImageProcessor( crop_size=2_24 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __magic_name__ ( self : List[str] ) -> Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str ={ '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } SCREAMING_SNAKE_CASE__ : str =PriorTransformer(**__lowercase ) return model @property def __magic_name__ ( self : Tuple ) -> List[str]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE__ : str =ShapERenderer(**__lowercase ) return model def __magic_name__ ( self : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.dummy_prior SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_encoder SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_image_processor SCREAMING_SNAKE_CASE__ : Tuple =self.dummy_renderer SCREAMING_SNAKE_CASE__ : int =HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=__lowercase , clip_sample=__lowercase , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ : Any ={ '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __magic_name__ ( self : Any , __lowercase : List[str] , __lowercase : Any=0 ) -> Any: SCREAMING_SNAKE_CASE__ : int =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : List[str] =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : List[str] ) -> str: SCREAMING_SNAKE_CASE__ : int ='''cpu''' SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : str =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] =np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __magic_name__ ( self : List[Any] ) -> List[str]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch_device == '''cpu''' SCREAMING_SNAKE_CASE__ : Optional[Any] =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowercase , relax_max_difference=__lowercase , ) def __magic_name__ ( self : Dict ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =1 SCREAMING_SNAKE_CASE__ : List[str] =2 SCREAMING_SNAKE_CASE__ : Dict =self.get_dummy_inputs(__lowercase ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ : Tuple =batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ : List[Any] =pipe(**__lowercase , num_images_per_prompt=__lowercase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Optional[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) SCREAMING_SNAKE_CASE__ : Dict =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) SCREAMING_SNAKE_CASE__ : List[Any] =ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) SCREAMING_SNAKE_CASE__ : Tuple =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple =pipe( __lowercase , generator=__lowercase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Any , __lowercase : Dict , __lowercase : Optional[int]=7 , __lowercase : Dict=3 , __lowercase : Optional[Any]=18 , __lowercase : int=30 , __lowercase : Dict=4_00 , __lowercase : Any=True , __lowercase : Optional[Any]=None , __lowercase : Optional[int]=True , __lowercase : Optional[int]=None , __lowercase : str=True , ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] =size if size is not None else {'''shortest_edge''': 20} SCREAMING_SNAKE_CASE__ : Optional[Any] =crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} SCREAMING_SNAKE_CASE__ : List[Any] =parent SCREAMING_SNAKE_CASE__ : int =batch_size SCREAMING_SNAKE_CASE__ : Any =num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[str] =min_resolution SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_resolution SCREAMING_SNAKE_CASE__ : Tuple =do_resize SCREAMING_SNAKE_CASE__ : str =size SCREAMING_SNAKE_CASE__ : int =do_center_crop SCREAMING_SNAKE_CASE__ : str =crop_size SCREAMING_SNAKE_CASE__ : Optional[int] =do_flip_channel_order def __magic_name__ ( self : str ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = MobileViTImageProcessor if is_vision_available() else None def __magic_name__ ( self : Union[str, Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =MobileViTImageProcessingTester(self ) @property def __magic_name__ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def __magic_name__ ( self : List[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowercase , '''size''' ) ) self.assertTrue(hasattr(__lowercase , '''do_center_crop''' ) ) self.assertTrue(hasattr(__lowercase , '''center_crop''' ) ) self.assertTrue(hasattr(__lowercase , '''do_flip_channel_order''' ) ) def __magic_name__ ( self : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) SCREAMING_SNAKE_CASE__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def __magic_name__ ( self : List[Any] ) -> Union[str, Any]: pass def __magic_name__ ( self : Any ) -> Optional[Any]: # Initialize image_processing SCREAMING_SNAKE_CASE__ : Any =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : List[str] =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[int] =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __magic_name__ ( self : Dict ) -> List[Any]: # Initialize image_processing SCREAMING_SNAKE_CASE__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , numpify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] =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 SCREAMING_SNAKE_CASE__ : Optional[int] =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __magic_name__ ( self : str ) -> Dict: # Initialize image_processing SCREAMING_SNAKE_CASE__ : Optional[int] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , torchify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : str =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any =image_processing(__lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_bigcode""" snake_case_ = ["""past_key_values"""] snake_case_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Any , __lowercase : Any=5_02_57 , __lowercase : int=10_24 , __lowercase : List[str]=7_68 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : List[str]=None , __lowercase : int="gelu_pytorch_tanh" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=1e-5 , __lowercase : List[str]=0.02 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=5_02_56 , __lowercase : List[Any]=5_02_56 , __lowercase : Union[str, Any]=True , __lowercase : List[str]=True , __lowercase : Dict=True , **__lowercase : List[Any] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_positions SCREAMING_SNAKE_CASE__ : Dict =n_embd SCREAMING_SNAKE_CASE__ : Dict =n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_head SCREAMING_SNAKE_CASE__ : List[str] =n_inner SCREAMING_SNAKE_CASE__ : List[str] =activation_function SCREAMING_SNAKE_CASE__ : List[Any] =resid_pdrop SCREAMING_SNAKE_CASE__ : List[Any] =embd_pdrop SCREAMING_SNAKE_CASE__ : List[str] =attn_pdrop SCREAMING_SNAKE_CASE__ : Dict =layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =scale_attn_weights SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Dict =attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : int =scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Dict =multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] =eos_token_id super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : int = 3, UpperCamelCase__ : int = 7, UpperCamelCase__ : int = 1_0_0_0_0_0_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =0 SCREAMING_SNAKE_CASE__ : Optional[int] =1 for current_denominator in range(1, limit + 1 ): SCREAMING_SNAKE_CASE__ : Dict =current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: SCREAMING_SNAKE_CASE__ : Optional[Any] =current_numerator SCREAMING_SNAKE_CASE__ : Optional[int] =current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_0_0_0_0_0_0))
665
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =size SCREAMING_SNAKE_CASE__ : List[Any] =[0] * size SCREAMING_SNAKE_CASE__ : str =[0] * size @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return index | (index + 1) @staticmethod def __magic_name__ ( __lowercase : int ) -> int: return (index & (index + 1)) - 1 def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[str] =value while index < self.size: SCREAMING_SNAKE_CASE__ : Any =self.get_prev(__lowercase ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : List[str] =value else: SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_next(__lowercase ) def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : int ) -> int: right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : str =0 while left <= right: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.get_prev(__lowercase ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[Any] =max(__lowercase , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Any =current_left else: SCREAMING_SNAKE_CASE__ : Optional[Any] =max(__lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
665
1
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""vqvae"""] def __init__( self : int , __lowercase : AutoencoderKL , __lowercase : UNetaDConditionModel , __lowercase : Mel , __lowercase : Union[DDIMScheduler, DDPMScheduler] , ) -> int: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase , mel=__lowercase , vqvae=__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return 50 if isinstance(self.scheduler , __lowercase ) else 10_00 @torch.no_grad() def __call__( self : Dict , __lowercase : int = 1 , __lowercase : str = None , __lowercase : np.ndarray = None , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = None , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : float = 0 , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : torch.Tensor = None , __lowercase : torch.Tensor = None , __lowercase : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: SCREAMING_SNAKE_CASE__ : Optional[Any] =steps or self.get_default_steps() self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE__ : Optional[int] =randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowercase , device=self.device , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =noise SCREAMING_SNAKE_CASE__ : List[str] =None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.mel.audio_slice_to_image(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE__ : int =(input_image / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =self.vqvae.encode(torch.unsqueeze(__lowercase , 0 ) ).latent_dist.sample( generator=__lowercase )[0] SCREAMING_SNAKE_CASE__ : int =self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE__ : Optional[Any] =int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : Tuple =int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowercase ): SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase , __lowercase )['''sample'''] else: SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase )['''sample'''] if isinstance(self.scheduler , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , eta=__lowercase , generator=__lowercase , )['''prev_sample'''] else: SCREAMING_SNAKE_CASE__ : Any =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , generator=__lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE__ : List[str] =mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE__ : str =1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE__ : int =self.vqvae.decode(__lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE__ : Dict =(images * 2_55).round().astype('''uint8''' ) SCREAMING_SNAKE_CASE__ : Any =list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[self.mel.image_to_audio(__lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowercase ) ) @torch.no_grad() def __magic_name__ ( self : Optional[int] , __lowercase : List[Image.Image] , __lowercase : int = 50 ) -> np.ndarray: assert isinstance(self.scheduler , __lowercase ) self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE__ : str =(sample / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : str =torch.Tensor(__lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE__ : Tuple =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE__ : Any =self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : int =( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : int =1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Optional[Any] =self.unet(__lowercase , __lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =(1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE__ : str =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE__ : Any =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __magic_name__ ( __lowercase : torch.Tensor , __lowercase : torch.Tensor , __lowercase : float ) -> torch.Tensor: SCREAMING_SNAKE_CASE__ : Optional[int] =acos(torch.dot(torch.flatten(__lowercase ) , torch.flatten(__lowercase ) ) / torch.norm(__lowercase ) / torch.norm(__lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowercase ) + sin(alpha * theta ) * xa / sin(__lowercase )
665
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = ["""vqvae"""] def __init__( self : int , __lowercase : AutoencoderKL , __lowercase : UNetaDConditionModel , __lowercase : Mel , __lowercase : Union[DDIMScheduler, DDPMScheduler] , ) -> int: super().__init__() self.register_modules(unet=__lowercase , scheduler=__lowercase , mel=__lowercase , vqvae=__lowercase ) def __magic_name__ ( self : List[str] ) -> int: return 50 if isinstance(self.scheduler , __lowercase ) else 10_00 @torch.no_grad() def __call__( self : Dict , __lowercase : int = 1 , __lowercase : str = None , __lowercase : np.ndarray = None , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = None , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : float = 0 , __lowercase : torch.Generator = None , __lowercase : float = 0 , __lowercase : torch.Tensor = None , __lowercase : torch.Tensor = None , __lowercase : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: SCREAMING_SNAKE_CASE__ : Optional[Any] =steps or self.get_default_steps() self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE__ : Union[str, Any] =(self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE__ : Optional[int] =randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowercase , device=self.device , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =noise SCREAMING_SNAKE_CASE__ : List[str] =None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Dict =self.mel.audio_slice_to_image(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE__ : int =(input_image / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =self.vqvae.encode(torch.unsqueeze(__lowercase , 0 ) ).latent_dist.sample( generator=__lowercase )[0] SCREAMING_SNAKE_CASE__ : int =self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE__ : Optional[Any] =int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : Tuple =int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE__ : int =self.scheduler.add_noise(__lowercase , __lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowercase ): SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase , __lowercase )['''sample'''] else: SCREAMING_SNAKE_CASE__ : str =self.unet(__lowercase , __lowercase )['''sample'''] if isinstance(self.scheduler , __lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , eta=__lowercase , generator=__lowercase , )['''prev_sample'''] else: SCREAMING_SNAKE_CASE__ : Any =self.scheduler.step( model_output=__lowercase , timestep=__lowercase , sample=__lowercase , generator=__lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] =mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE__ : List[str] =mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE__ : str =1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE__ : int =self.vqvae.decode(__lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] =images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE__ : Dict =(images * 2_55).round().astype('''uint8''' ) SCREAMING_SNAKE_CASE__ : Any =list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[self.mel.image_to_audio(__lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowercase ) ) @torch.no_grad() def __magic_name__ ( self : Optional[int] , __lowercase : List[Image.Image] , __lowercase : int = 50 ) -> np.ndarray: assert isinstance(self.scheduler , __lowercase ) self.scheduler.set_timesteps(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE__ : str =(sample / 2_55) * 2 - 1 SCREAMING_SNAKE_CASE__ : str =torch.Tensor(__lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE__ : Tuple =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE__ : Any =self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : int =( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : int =1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Optional[Any] =self.unet(__lowercase , __lowercase )['''sample'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =(1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE__ : str =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE__ : Any =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __magic_name__ ( __lowercase : torch.Tensor , __lowercase : torch.Tensor , __lowercase : float ) -> torch.Tensor: SCREAMING_SNAKE_CASE__ : Optional[int] =acos(torch.dot(torch.flatten(__lowercase ) , torch.flatten(__lowercase ) ) / torch.norm(__lowercase ) / torch.norm(__lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowercase ) + sin(alpha * theta ) * xa / sin(__lowercase )
665
1
'''simple docstring''' import os def _a( ): '''simple docstring''' with open(os.path.dirname(UpperCamelCase__ ) + '''/p022_names.txt''' ) as file: SCREAMING_SNAKE_CASE__ : int =str(file.readlines()[0] ) SCREAMING_SNAKE_CASE__ : List[str] =names.replace('''"''', '''''' ).split(''',''' ) names.sort() SCREAMING_SNAKE_CASE__ : Dict =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 for i, name in enumerate(UpperCamelCase__ ): for letter in name: name_score += ord(UpperCamelCase__ ) - 6_4 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE__ : str =0 return total_score if __name__ == "__main__": print(solution())
665
'''simple docstring''' from math import isqrt def _a( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =[True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Any =False return [i for i in range(2, UpperCamelCase__ ) if is_prime[i]] def _a( UpperCamelCase__ : int = 1_0**8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =calculate_prime_numbers(max_number // 2 ) SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Optional[int] =len(UpperCamelCase__ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =0 # if input_string is "aba" than new_input_string become "a|b|a" SCREAMING_SNAKE_CASE__ : Optional[Any] ='''''' SCREAMING_SNAKE_CASE__ : Dict ='''''' # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(UpperCamelCase__ ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =0, 0 # length[i] shows the length of palindromic substring with center i SCREAMING_SNAKE_CASE__ : Tuple =[1 for i in range(len(UpperCamelCase__ ) )] # for each character in new_string find corresponding palindromic string SCREAMING_SNAKE_CASE__ : Tuple =0 for j in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ : str =1 if j > r else min(length[l + r - j] // 2, r - j + 1 ) while ( j - k >= 0 and j + k < len(UpperCamelCase__ ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 SCREAMING_SNAKE_CASE__ : Dict =2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: SCREAMING_SNAKE_CASE__ : Optional[int] =j - k + 1 # noqa: E741 SCREAMING_SNAKE_CASE__ : Union[str, Any] =j + k - 1 # update max_length and start position if max_length < length[j]: SCREAMING_SNAKE_CASE__ : Any =length[j] SCREAMING_SNAKE_CASE__ : List[str] =j # create that string SCREAMING_SNAKE_CASE__ : List[Any] =new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = SpeechTaTokenizer snake_case_ = False snake_case_ = True def __magic_name__ ( self : int ) -> Any: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[Any] =SpeechTaTokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken('''<mask>''' , lstrip=__lowercase , rstrip=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Dict , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''this is a test''' SCREAMING_SNAKE_CASE__ : int ='''this is a test''' return input_text, output_text def __magic_name__ ( self : List[Any] , __lowercase : int , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=20 , __lowercase : Any=5 ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_input_output_texts(__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.decode(__lowercase , clean_up_tokenization_spaces=__lowercase ) return text, ids def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] ='''<pad>''' SCREAMING_SNAKE_CASE__ : Optional[int] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__lowercase ) , 81 ) def __magic_name__ ( self : Dict ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Any =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ : int =['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.add_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ : str ={'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} SCREAMING_SNAKE_CASE__ : int =tokenizer.add_special_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size_a + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __magic_name__ ( self : Optional[Any] ) -> Any: pass def __magic_name__ ( self : List[str] ) -> List[Any]: pass def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_ids(__lowercase ) # fmt: off self.assertListEqual(__lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.convert_ids_to_tokens(__lowercase ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __magic_name__ ( self : List[str] ) -> List[str]: # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE__ : List[Any] =[ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off SCREAMING_SNAKE_CASE__ : str ={ '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__lowercase , )
665
1
'''simple docstring''' from __future__ import annotations import queue class __SCREAMING_SNAKE_CASE : def __init__( self : str , __lowercase : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =data SCREAMING_SNAKE_CASE__ : List[str] =None SCREAMING_SNAKE_CASE__ : Tuple =None def _a( ): '''simple docstring''' print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE__ : Tuple =input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE__ : queue.Queue =queue.Queue() SCREAMING_SNAKE_CASE__ : int =TreeNode(int(UpperCamelCase__ ) ) q.put(UpperCamelCase__ ) while not q.empty(): SCREAMING_SNAKE_CASE__ : Dict =q.get() SCREAMING_SNAKE_CASE__ : str =f"Enter the left node of {node_found.data}: " SCREAMING_SNAKE_CASE__ : List[Any] =input(UpperCamelCase__ ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE__ : Tuple =TreeNode(int(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : List[str] =left_node q.put(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =f"Enter the right node of {node_found.data}: " SCREAMING_SNAKE_CASE__ : Union[str, Any] =input(UpperCamelCase__ ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE__ : Optional[int] =TreeNode(int(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : str =right_node q.put(UpperCamelCase__ ) raise def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return print(node.data, end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return in_order(node.left ) print(node.data, end=''',''' ) in_order(node.right ) def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data, end=''',''' ) def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return SCREAMING_SNAKE_CASE__ : queue.Queue =queue.Queue() q.put(UpperCamelCase__ ) while not q.empty(): SCREAMING_SNAKE_CASE__ : int =q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return SCREAMING_SNAKE_CASE__ : queue.Queue =queue.Queue() q.put(UpperCamelCase__ ) while not q.empty(): SCREAMING_SNAKE_CASE__ : Optional[int] =[] while not q.empty(): SCREAMING_SNAKE_CASE__ : str =q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(UpperCamelCase__ ) def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return SCREAMING_SNAKE_CASE__ : list[TreeNode] =[] SCREAMING_SNAKE_CASE__ : List[Any] =node while n or stack: while n: # start from root node, find its left child print(n.data, end=''',''' ) stack.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE__ : List[Any] =stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE__ : str =n.right def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return SCREAMING_SNAKE_CASE__ : list[TreeNode] =[] SCREAMING_SNAKE_CASE__ : List[Any] =node while n or stack: while n: stack.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =n.left SCREAMING_SNAKE_CASE__ : int =stack.pop() print(n.data, end=''',''' ) SCREAMING_SNAKE_CASE__ : Any =n.right def _a( UpperCamelCase__ : TreeNode ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ) or not node: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =[], [] SCREAMING_SNAKE_CASE__ : Optional[Any] =node stacka.append(UpperCamelCase__ ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE__ : Any =stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(UpperCamelCase__ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data, end=''',''' ) def _a( UpperCamelCase__ : str = "", UpperCamelCase__ : List[str]=5_0, UpperCamelCase__ : List[Any]="*" ): '''simple docstring''' if not s: return "\n" + width * char SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =divmod(width - len(UpperCamelCase__ ) - 2, 2 ) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) a_ = build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 5_0 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
665
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Optional[int] , __lowercase : str=13 , __lowercase : int=10 , __lowercase : List[Any]=3 , __lowercase : List[str]=2 , __lowercase : int=2 , __lowercase : Dict=True , __lowercase : Optional[Any]=True , __lowercase : int=32 , __lowercase : List[Any]=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Optional[Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Tuple=0.1 , __lowercase : Dict=10 , __lowercase : int=0.02 , __lowercase : str="divided_space_time" , __lowercase : Union[str, Any]=None , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =parent SCREAMING_SNAKE_CASE__ : List[str] =batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_size SCREAMING_SNAKE_CASE__ : List[Any] =num_channels SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Tuple =num_frames SCREAMING_SNAKE_CASE__ : List[Any] =is_training SCREAMING_SNAKE_CASE__ : List[str] =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : int =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =intermediate_size SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] =initializer_range SCREAMING_SNAKE_CASE__ : Any =scope SCREAMING_SNAKE_CASE__ : int =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE__ : List[str] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str =(num_frames) * self.num_patches_per_frame + 1 def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =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 , ) SCREAMING_SNAKE_CASE__ : List[Any] =self.num_labels return config def __magic_name__ ( self : int , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Tuple =TimesformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : List[str] , __lowercase : str , __lowercase : Tuple , __lowercase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =TimesformerForVideoClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase ) # verify the logits shape SCREAMING_SNAKE_CASE__ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowercase ) def __magic_name__ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): 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 __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] =ConfigTester( self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int]=False ) -> int: SCREAMING_SNAKE_CASE__ : str =copy.deepcopy(__lowercase ) if return_labels: if model_class in get_values(__lowercase ): SCREAMING_SNAKE_CASE__ : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> Optional[int]: pass def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowercase ) @slow def __magic_name__ ( self : Optional[int] ) -> Optional[Any]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =TimesformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE__ : Optional[Any] =True SCREAMING_SNAKE_CASE__ : str =False SCREAMING_SNAKE_CASE__ : Tuple =True SCREAMING_SNAKE_CASE__ : Dict =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : List[str] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.attentions self.assertEqual(len(__lowercase ) , 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] , ) SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[int] =True SCREAMING_SNAKE_CASE__ : Union[str, Any] =True SCREAMING_SNAKE_CASE__ : Optional[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[str] =outputs.attentions self.assertEqual(len(__lowercase ) , 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 __magic_name__ ( self : Tuple ) -> List[Any]: def check_hidden_states_output(__lowercase : Tuple , __lowercase : Dict , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : List[Any] =model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int =model(**self._prepare_for_class(__lowercase , __lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =outputs.hidden_states SCREAMING_SNAKE_CASE__ : Tuple =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowercase ) , __lowercase ) SCREAMING_SNAKE_CASE__ : int =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] =True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) SCREAMING_SNAKE_CASE__ : Any =np.load(UpperCamelCase__ ) return list(UpperCamelCase__ ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Any ) -> List[str]: # 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 __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.default_image_processor SCREAMING_SNAKE_CASE__ : Tuple =prepare_video() SCREAMING_SNAKE_CASE__ : Any =image_processor(video[:8] , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] =model(**__lowercase ) # verify the logits SCREAMING_SNAKE_CASE__ : List[str] =torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1e-4 ) )
665
1
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =0 SCREAMING_SNAKE_CASE__ : str =len(UpperCamelCase__ ) for i in range(n - 1 ): for j in range(i + 1, UpperCamelCase__ ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def _a( UpperCamelCase__ : int ): '''simple docstring''' if len(UpperCamelCase__ ) <= 1: return arr, 0 SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) // 2 SCREAMING_SNAKE_CASE__ : List[Any] =arr[0:mid] SCREAMING_SNAKE_CASE__ : List[str] =arr[mid:] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =count_inversions_recursive(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =count_inversions_recursive(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =_count_cross_inversions(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =inversion_p + inversions_q + cross_inversions return c, num_inversions def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =[] SCREAMING_SNAKE_CASE__ : Optional[Any] =0 while i < len(UpperCamelCase__ ) and j < len(UpperCamelCase__ ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(UpperCamelCase__ ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(UpperCamelCase__ ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] =[1_0, 2, 1, 5, 5, 2, 1_1] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) SCREAMING_SNAKE_CASE__ : Dict =count_inversions_bf(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =count_inversions_recursive(UpperCamelCase__ ) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''', UpperCamelCase__ ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() SCREAMING_SNAKE_CASE__ : Optional[Any] =count_inversions_bf(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =count_inversions_recursive(UpperCamelCase__ ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''', UpperCamelCase__ ) # an empty list should also have zero inversions SCREAMING_SNAKE_CASE__ : Dict =[] SCREAMING_SNAKE_CASE__ : List[str] =count_inversions_bf(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =count_inversions_recursive(UpperCamelCase__ ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''', UpperCamelCase__ ) if __name__ == "__main__": main()
665
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } a_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = BertTokenizer def __init__( self : int , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : str=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Tuple="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : Union[str, Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : str=None , **__lowercase : Any , ) -> Optional[Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) SCREAMING_SNAKE_CASE__ : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowercase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowercase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowercase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : int =getattr(__lowercase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE__ : Any =do_lower_case SCREAMING_SNAKE_CASE__ : Any =strip_accents SCREAMING_SNAKE_CASE__ : Dict =tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : Union[str, Any] =normalizer_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =do_lower_case def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Union[str, Any]=None ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =[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 __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
665
1
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : List[str] , __lowercase : Any=2 , __lowercase : str=32 , __lowercase : Optional[Any]=16 , __lowercase : int=3 , __lowercase : Tuple=True , __lowercase : str=True , __lowercase : Dict=32 , __lowercase : Union[str, Any]=4 , __lowercase : Dict=[0, 1, 2, 3] , __lowercase : Dict=4 , __lowercase : List[str]=37 , __lowercase : Any="gelu" , __lowercase : Dict=0.1 , __lowercase : List[str]=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=3 , __lowercase : Dict=[1, 3_84, 24, 24] , __lowercase : Tuple=True , __lowercase : List[Any]=None , ) -> Any: SCREAMING_SNAKE_CASE__ : str =parent SCREAMING_SNAKE_CASE__ : str =batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =image_size SCREAMING_SNAKE_CASE__ : int =patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] =num_channels SCREAMING_SNAKE_CASE__ : Tuple =is_training SCREAMING_SNAKE_CASE__ : str =use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] =num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] =backbone_out_indices SCREAMING_SNAKE_CASE__ : List[Any] =num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] =intermediate_size SCREAMING_SNAKE_CASE__ : str =hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =initializer_range SCREAMING_SNAKE_CASE__ : Dict =num_labels SCREAMING_SNAKE_CASE__ : List[str] =backbone_featmap_shape SCREAMING_SNAKE_CASE__ : int =scope SCREAMING_SNAKE_CASE__ : List[str] =is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Optional[Any] =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Any =num_patches + 1 def __magic_name__ ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Dict =self.get_config() return config, pixel_values, labels def __magic_name__ ( self : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str ={ '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 1_92, 3_84, 7_68], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowercase , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__lowercase , backbone_featmap_shape=self.backbone_featmap_shape , ) def __magic_name__ ( self : List[str] , __lowercase : Tuple , __lowercase : List[str] , __lowercase : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =DPTModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Dict =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : int , __lowercase : Dict , __lowercase : List[Any] , __lowercase : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE__ : Any =self.num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] =DPTForDepthEstimation(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __magic_name__ ( self : str , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[str] =self.num_labels SCREAMING_SNAKE_CASE__ : List[str] =DPTForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : int =model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __magic_name__ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] ={'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): snake_case_ = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () snake_case_ = ( { """depth-estimation""": DPTForDepthEstimation, """feature-extraction""": DPTModel, """image-segmentation""": DPTForSemanticSegmentation, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False def __magic_name__ ( self : Union[str, Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =DPTModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple =ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def __magic_name__ ( self : Union[str, Any] ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ) -> List[str]: pass def __magic_name__ ( self : Union[str, Any] ) -> str: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple =model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : int =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def __magic_name__ ( self : Optional[Any] ) -> int: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] =model_class(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Dict =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Dict =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def __magic_name__ ( self : List[Any] ) -> str: SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__lowercase ) def __magic_name__ ( self : int ) -> Dict: SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) def __magic_name__ ( self : Optional[int] ) -> str: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Tuple =True if model_class in get_values(__lowercase ): continue SCREAMING_SNAKE_CASE__ : Optional[int] =model_class(__lowercase ) model.to(__lowercase ) model.train() SCREAMING_SNAKE_CASE__ : Union[str, Any] =self._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) SCREAMING_SNAKE_CASE__ : int =model(**__lowercase ).loss loss.backward() def __magic_name__ ( self : Any ) -> str: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] =False SCREAMING_SNAKE_CASE__ : List[Any] =True if model_class in get_values(__lowercase ) or not model_class.supports_gradient_checkpointing: continue SCREAMING_SNAKE_CASE__ : Optional[int] =model_class(__lowercase ) model.to(__lowercase ) model.gradient_checkpointing_enable() model.train() SCREAMING_SNAKE_CASE__ : List[str] =self._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) SCREAMING_SNAKE_CASE__ : int =model(**__lowercase ).loss loss.backward() def __magic_name__ ( self : Dict ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Tuple =_config_zero_init(__lowercase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str =model_class(config=__lowercase ) # Skip the check for the backbone SCREAMING_SNAKE_CASE__ : List[str] =[] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": SCREAMING_SNAKE_CASE__ : Optional[int] =[F"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __magic_name__ ( self : Optional[int] ) -> Tuple: pass @slow def __magic_name__ ( self : str ) -> Optional[int]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: SCREAMING_SNAKE_CASE__ : str =DPTModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __magic_name__ ( self : Dict ) -> List[str]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int ='''add''' with self.assertRaises(__lowercase ): SCREAMING_SNAKE_CASE__ : str =DPTForDepthEstimation(__lowercase ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Tuple ) -> str: SCREAMING_SNAKE_CASE__ : Optional[Any] =DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) SCREAMING_SNAKE_CASE__ : Tuple =DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =prepare_img() SCREAMING_SNAKE_CASE__ : Dict =image_processor(images=__lowercase , return_tensors='''pt''' ).to(__lowercase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] =model(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any =outputs.predicted_depth # verify the predicted depth SCREAMING_SNAKE_CASE__ : int =torch.Size((1, 3_84, 3_84) ) self.assertEqual(predicted_depth.shape , __lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00 , __lowercase , atol=1e-4 ) )
665
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters a_ = False a_ = False def _a( UpperCamelCase__ : Namespace ): '''simple docstring''' return TrainCommand(UpperCamelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Any: SCREAMING_SNAKE_CASE__ : Union[str, Any] =parser.add_parser('''train''' , help='''CLI tool to train a model on a task.''' ) train_parser.add_argument( '''--train_data''' , type=__lowercase , required=__lowercase , help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.''' , ) train_parser.add_argument( '''--column_label''' , type=__lowercase , default=0 , help='''Column of the dataset csv file with example labels.''' ) train_parser.add_argument( '''--column_text''' , type=__lowercase , default=1 , help='''Column of the dataset csv file with example texts.''' ) train_parser.add_argument( '''--column_id''' , type=__lowercase , default=2 , help='''Column of the dataset csv file with example ids.''' ) train_parser.add_argument( '''--skip_first_row''' , action='''store_true''' , help='''Skip the first row of the csv file (headers).''' ) train_parser.add_argument('''--validation_data''' , type=__lowercase , default='''''' , help='''path to validation dataset.''' ) train_parser.add_argument( '''--validation_split''' , type=__lowercase , default=0.1 , help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.''' , ) train_parser.add_argument('''--output''' , type=__lowercase , default='''./''' , help='''path to saved the trained model.''' ) train_parser.add_argument( '''--task''' , type=__lowercase , default='''text_classification''' , help='''Task to train the model on.''' ) train_parser.add_argument( '''--model''' , type=__lowercase , default='''bert-base-uncased''' , help='''Model\'s name or path to stored model.''' ) train_parser.add_argument('''--train_batch_size''' , type=__lowercase , default=32 , help='''Batch size for training.''' ) train_parser.add_argument('''--valid_batch_size''' , type=__lowercase , default=64 , help='''Batch size for validation.''' ) train_parser.add_argument('''--learning_rate''' , type=__lowercase , default=3e-5 , help='''Learning rate.''' ) train_parser.add_argument('''--adam_epsilon''' , type=__lowercase , default=1e-08 , help='''Epsilon for Adam optimizer.''' ) train_parser.set_defaults(func=__lowercase ) def __init__( self : Tuple , __lowercase : Namespace ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =logging.get_logger('''transformers-cli/training''' ) SCREAMING_SNAKE_CASE__ : int ='''tf''' if is_tf_available() else '''torch''' os.makedirs(args.output , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : Any =args.output SCREAMING_SNAKE_CASE__ : str =args.column_label SCREAMING_SNAKE_CASE__ : List[Any] =args.column_text SCREAMING_SNAKE_CASE__ : Tuple =args.column_id self.logger.info(F"Loading {args.task} pipeline for {args.model}" ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : List[str] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"Loading dataset from {args.train_data}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =None if args.validation_data: self.logger.info(F"Loading validation dataset from {args.validation_data}" ) SCREAMING_SNAKE_CASE__ : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =args.validation_split SCREAMING_SNAKE_CASE__ : List[Any] =args.train_batch_size SCREAMING_SNAKE_CASE__ : Any =args.valid_batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =args.learning_rate SCREAMING_SNAKE_CASE__ : int =args.adam_epsilon def __magic_name__ ( self : Any ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __magic_name__ ( self : Optional[int] ) -> Tuple: raise NotImplementedError def __magic_name__ ( self : Dict ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
665
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process a_ = logging.getLogger(__name__) def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : List[Any] ): '''simple docstring''' return (preds == labels).mean() @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) snake_case_ = field( default=lowerCamelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) snake_case_ = field( default=lowerCamelCase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) snake_case_ = field( default=lowerCamelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys() )} ) snake_case_ = field(metadata={"""help""": """Should contain the data files for the task."""} ) snake_case_ = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) snake_case_ = field( default=lowerCamelCase , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =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.''' ) # 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''', UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE__ : List[Any] =processors[data_args.task_name]() SCREAMING_SNAKE_CASE__ : int =processor.get_labels() SCREAMING_SNAKE_CASE__ : Tuple =len(UpperCamelCase__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=UpperCamelCase__, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE__ : Optional[Any] =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, ) SCREAMING_SNAKE_CASE__ : Tuple =AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=UpperCamelCase__, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE__ : Tuple =( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=UpperCamelCase__, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=UpperCamelCase__, task=data_args.task_name, 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 compute_metrics(UpperCamelCase__ : EvalPrediction ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(UpperCamelCase__, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE__ : Optional[Any] =DataCollatorWithPadding(UpperCamelCase__, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Dict =Trainer( model=UpperCamelCase__, args=UpperCamelCase__, train_dataset=UpperCamelCase__, eval_dataset=UpperCamelCase__, compute_metrics=UpperCamelCase__, data_collator=UpperCamelCase__, ) # 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_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE__ : Dict ={} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE__ : List[str] =trainer.evaluate() SCREAMING_SNAKE_CASE__ : str =os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(UpperCamelCase__, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', UpperCamelCase__, UpperCamelCase__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(UpperCamelCase__ ) return results def _a( UpperCamelCase__ : Optional[int] ): '''simple docstring''' main() if __name__ == "__main__": main()
665
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = KandinskyVaaImgaImgPipeline snake_case_ = ["""image_embeds""", """negative_image_embeds""", """image"""] snake_case_ = [ """image_embeds""", """negative_image_embeds""", """image""", ] snake_case_ = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case_ = False @property def __magic_name__ ( self : List[str] ) -> Tuple: return 32 @property def __magic_name__ ( self : List[str] ) -> str: return 32 @property def __magic_name__ ( self : Any ) -> Optional[int]: return self.time_input_dim @property def __magic_name__ ( self : List[Any] ) -> int: return self.time_input_dim * 4 @property def __magic_name__ ( self : Tuple ) -> Optional[int]: return 1_00 @property def __magic_name__ ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDConditionModel(**__lowercase ) return model @property def __magic_name__ ( self : Dict ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __magic_name__ ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] =VQModel(**self.dummy_movq_kwargs ) return model def __magic_name__ ( self : str ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] =self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] =self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ : str =DDIMScheduler(**__lowercase ) SCREAMING_SNAKE_CASE__ : Any ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __magic_name__ ( self : str , __lowercase : Optional[Any] , __lowercase : Any=0 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[Any] =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any =Image.fromarray(np.uinta(__lowercase ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(__lowercase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ : Dict =torch.manual_seed(__lowercase ) else: SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) SCREAMING_SNAKE_CASE__ : str ={ '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] ='''cpu''' SCREAMING_SNAKE_CASE__ : Tuple =self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict =self.pipeline_class(**__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =pipe(**self.get_dummy_inputs(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] SCREAMING_SNAKE_CASE__ : List[Any] =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple =np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : int ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : str =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ : List[Any] ='''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ : Optional[int] =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ : int =output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
665
1
'''simple docstring''' from __future__ import annotations def _a( UpperCamelCase__ : list[int] ): # This function is recursive '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =len(UpperCamelCase__ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else SCREAMING_SNAKE_CASE__ : int =array[0] SCREAMING_SNAKE_CASE__ : List[str] =False SCREAMING_SNAKE_CASE__ : Dict =1 SCREAMING_SNAKE_CASE__ : list[int] =[] while not is_found and i < array_length: if array[i] < pivot: SCREAMING_SNAKE_CASE__ : List[Any] =True SCREAMING_SNAKE_CASE__ : Tuple =[element for element in array[i:] if element >= array[i]] SCREAMING_SNAKE_CASE__ : Optional[int] =longest_subsequence(UpperCamelCase__ ) if len(UpperCamelCase__ ) > len(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =temp_array else: i += 1 SCREAMING_SNAKE_CASE__ : int =[element for element in array[1:] if element >= pivot] SCREAMING_SNAKE_CASE__ : Tuple =[pivot, *longest_subsequence(UpperCamelCase__ )] if len(UpperCamelCase__ ) > len(UpperCamelCase__ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
665
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ = TypeVar('T') class __SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case_ = 42 # Cache store of keys snake_case_ = 42 # References of the keys in cache snake_case_ = 10 # Maximum capacity of cache def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : Any =deque() SCREAMING_SNAKE_CASE__ : str =set() if not n: SCREAMING_SNAKE_CASE__ : Optional[Any] =sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =n def __magic_name__ ( self : List[str] , __lowercase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE__ : int =self.dq_store.pop() self.key_reference.remove(__lowercase ) else: self.dq_store.remove(__lowercase ) self.dq_store.appendleft(__lowercase ) self.key_reference.add(__lowercase ) def __magic_name__ ( self : Union[str, Any] ) -> None: for k in self.dq_store: print(__lowercase ) def __repr__( self : List[Any] ) -> str: return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() a_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
665
1
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING a_ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Any , *__lowercase : List[Any] , **__lowercase : List[Any] ) -> Union[str, Any]: super().__init__(*__lowercase , **__lowercase ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __magic_name__ ( self : Union[str, Any] , __lowercase : str=None , __lowercase : str=None , __lowercase : Any=None ) -> Any: SCREAMING_SNAKE_CASE__ : List[Any] ={} SCREAMING_SNAKE_CASE__ : Tuple ={} if prompt is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =prompt if generate_kwargs is not None: SCREAMING_SNAKE_CASE__ : int =generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: SCREAMING_SNAKE_CASE__ : Optional[int] ={} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,''' ''' please use only one''' ) SCREAMING_SNAKE_CASE__ : List[str] =max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : Any , __lowercase : Union[str, List[str], "Image.Image", List["Image.Image"]] , **__lowercase : Optional[int] ) -> Tuple: return super().__call__(__lowercase , **__lowercase ) def __magic_name__ ( self : int , __lowercase : str , __lowercase : str=None ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : str =load_image(__lowercase ) if prompt is not None: if not isinstance(__lowercase , __lowercase ): raise ValueError( F"Received an invalid text input, got - {type(__lowercase )} - but expected a single string. " '''Note also that one single text can be provided for conditional image to text generation.''' ) SCREAMING_SNAKE_CASE__ : Tuple =self.model.config.model_type if model_type == "git": SCREAMING_SNAKE_CASE__ : Any =self.image_processor(images=__lowercase , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : List[str] =self.tokenizer(text=__lowercase , add_special_tokens=__lowercase ).input_ids SCREAMING_SNAKE_CASE__ : Optional[int] =[self.tokenizer.cls_token_id] + input_ids SCREAMING_SNAKE_CASE__ : str =torch.tensor(__lowercase ).unsqueeze(0 ) model_inputs.update({'''input_ids''': input_ids} ) elif model_type == "pix2struct": SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.image_processor(images=__lowercase , header_text=__lowercase , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation SCREAMING_SNAKE_CASE__ : List[str] =self.image_processor(images=__lowercase , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Dict =self.tokenizer(__lowercase , return_tensors=self.framework ) model_inputs.update(__lowercase ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: SCREAMING_SNAKE_CASE__ : List[Any] =self.image_processor(images=__lowercase , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: SCREAMING_SNAKE_CASE__ : List[Any] =None return model_inputs def __magic_name__ ( self : int , __lowercase : Any , __lowercase : Optional[int]=None ) -> Optional[int]: # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs['''input_ids'''] , __lowercase ) and all(x is None for x in model_inputs['''input_ids'''] ) ): SCREAMING_SNAKE_CASE__ : List[Any] =None if generate_kwargs is None: SCREAMING_SNAKE_CASE__ : Any ={} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. SCREAMING_SNAKE_CASE__ : int =model_inputs.pop(self.model.main_input_name ) SCREAMING_SNAKE_CASE__ : int =self.model.generate(__lowercase , **__lowercase , **__lowercase ) return model_outputs def __magic_name__ ( self : int , __lowercase : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Any =[] for output_ids in model_outputs: SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''generated_text''': self.tokenizer.decode( __lowercase , skip_special_tokens=__lowercase , ) } records.append(__lowercase ) return records
665
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a_ = list[list[float | int]] def _a( UpperCamelCase__ : Matrix, UpperCamelCase__ : Matrix ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(size + 1 )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : float for row in range(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Tuple =matrix[row][col] SCREAMING_SNAKE_CASE__ : Optional[int] =vector[row][0] SCREAMING_SNAKE_CASE__ : Any =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =0 while row < size and col < size: # pivoting SCREAMING_SNAKE_CASE__ : Any =max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCamelCase__, UpperCamelCase__ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =augmented[rowa][col] / augmented[row][col] SCREAMING_SNAKE_CASE__ : Tuple =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, UpperCamelCase__ ): for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =augmented[row][col] / augmented[col][col] for cola in range(UpperCamelCase__, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 1_0 )] for row in range(UpperCamelCase__ ) ] def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Matrix =[[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix =[[0] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Matrix SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int for x_val, y_val in enumerate(UpperCamelCase__ ): for col in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =(x_val + 1) ** (size - col - 1) SCREAMING_SNAKE_CASE__ : Dict =y_val SCREAMING_SNAKE_CASE__ : Optional[int] =solve(UpperCamelCase__, UpperCamelCase__ ) def interpolated_func(UpperCamelCase__ : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(UpperCamelCase__ ) ) return interpolated_func def _a( UpperCamelCase__ : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**1_0 ) def _a( UpperCamelCase__ : Callable[[int], int] = question_function, UpperCamelCase__ : int = 1_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[int] =[func(UpperCamelCase__ ) for x_val in range(1, order + 1 )] SCREAMING_SNAKE_CASE__ : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] SCREAMING_SNAKE_CASE__ : int =0 SCREAMING_SNAKE_CASE__ : Callable[[int], int] SCREAMING_SNAKE_CASE__ : int for poly in polynomials: SCREAMING_SNAKE_CASE__ : Any =1 while func(UpperCamelCase__ ) == poly(UpperCamelCase__ ): x_val += 1 ret += poly(UpperCamelCase__ ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
665
'''simple docstring''' def _a( UpperCamelCase__ : Optional[int], UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 SCREAMING_SNAKE_CASE__ : Union[str, Any] =len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Union[str, Any] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None SCREAMING_SNAKE_CASE__ : Optional[int] =sorted_collection[point] if current_item == item: return point else: if point < left: SCREAMING_SNAKE_CASE__ : Union[str, Any] =left SCREAMING_SNAKE_CASE__ : Optional[Any] =point elif point > right: SCREAMING_SNAKE_CASE__ : Optional[int] =right SCREAMING_SNAKE_CASE__ : Tuple =point else: if item < current_item: SCREAMING_SNAKE_CASE__ : str =point - 1 else: SCREAMING_SNAKE_CASE__ : Tuple =point + 1 return None def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None SCREAMING_SNAKE_CASE__ : Dict =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__, UpperCamelCase__, point + 1, UpperCamelCase__ ) def _a( UpperCamelCase__ : Dict ): '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys a_ = 0 if debug == 1: a_ = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') a_ = 6_7 a_ = interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
665
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def _a( UpperCamelCase__ : str ): '''simple docstring''' return EnvironmentCommand() def _a( UpperCamelCase__ : str ): '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @staticmethod def __magic_name__ ( __lowercase : ArgumentParser ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =parser.add_parser('''env''' ) download_parser.set_defaults(func=__lowercase ) download_parser.add_argument( '''--accelerate-config_file''' , default=__lowercase , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=__lowercase ) def __init__( self : Union[str, Any] , __lowercase : Optional[Any] , *__lowercase : List[Any] ) -> None: SCREAMING_SNAKE_CASE__ : str =accelerate_config_file def __magic_name__ ( self : int ) -> int: SCREAMING_SNAKE_CASE__ : Dict ='''not installed''' if is_safetensors_available(): import safetensors SCREAMING_SNAKE_CASE__ : Tuple =safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors SCREAMING_SNAKE_CASE__ : int =F"{safetensors.__version__} but is ignored because of PyTorch version too old." SCREAMING_SNAKE_CASE__ : Optional[int] ='''not installed''' SCREAMING_SNAKE_CASE__ : Tuple ='''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file SCREAMING_SNAKE_CASE__ : Dict =accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__lowercase ): SCREAMING_SNAKE_CASE__ : str =load_config_from_file(self._accelerate_config_file ).to_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] =( '''\n'''.join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__lowercase , __lowercase ) else F"\t{accelerate_config}" ) SCREAMING_SNAKE_CASE__ : Dict ='''not installed''' SCREAMING_SNAKE_CASE__ : Dict ='''NA''' if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : str =torch.__version__ SCREAMING_SNAKE_CASE__ : int =torch.cuda.is_available() SCREAMING_SNAKE_CASE__ : str ='''not installed''' SCREAMING_SNAKE_CASE__ : Dict ='''NA''' if is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : List[str] =tf.__version__ try: # deprecated in v2.1 SCREAMING_SNAKE_CASE__ : List[str] =tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool SCREAMING_SNAKE_CASE__ : int =bool(tf.config.list_physical_devices('''GPU''' ) ) SCREAMING_SNAKE_CASE__ : str ='''not installed''' SCREAMING_SNAKE_CASE__ : List[str] ='''not installed''' SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''not installed''' SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''NA''' if is_flax_available(): import flax import jax import jaxlib SCREAMING_SNAKE_CASE__ : List[Any] =flax.__version__ SCREAMING_SNAKE_CASE__ : int =jax.__version__ SCREAMING_SNAKE_CASE__ : Optional[int] =jaxlib.__version__ SCREAMING_SNAKE_CASE__ : int =jax.lib.xla_bridge.get_backend().platform SCREAMING_SNAKE_CASE__ : Dict ={ '''`transformers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Huggingface_hub version''': huggingface_hub.__version__, '''Safetensors version''': F"{safetensors_version}", '''Accelerate version''': F"{accelerate_version}", '''Accelerate config''': F"{accelerate_config_str}", '''PyTorch version (GPU?)''': F"{pt_version} ({pt_cuda_available})", '''Tensorflow version (GPU?)''': F"{tf_version} ({tf_cuda_available})", '''Flax version (CPU?/GPU?/TPU?)''': F"{flax_version} ({jax_backend})", '''Jax version''': F"{jax_version}", '''JaxLib version''': F"{jaxlib_version}", '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(__lowercase ) ) return info @staticmethod def __magic_name__ ( __lowercase : List[str] ) -> str: return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_bigcode""" snake_case_ = ["""past_key_values"""] snake_case_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Any , __lowercase : Any=5_02_57 , __lowercase : int=10_24 , __lowercase : List[str]=7_68 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : List[str]=None , __lowercase : int="gelu_pytorch_tanh" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=1e-5 , __lowercase : List[str]=0.02 , __lowercase : Tuple=True , __lowercase : Optional[Any]=True , __lowercase : Union[str, Any]=5_02_56 , __lowercase : List[Any]=5_02_56 , __lowercase : Union[str, Any]=True , __lowercase : List[str]=True , __lowercase : Dict=True , **__lowercase : List[Any] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_positions SCREAMING_SNAKE_CASE__ : Dict =n_embd SCREAMING_SNAKE_CASE__ : Dict =n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] =n_head SCREAMING_SNAKE_CASE__ : List[str] =n_inner SCREAMING_SNAKE_CASE__ : List[str] =activation_function SCREAMING_SNAKE_CASE__ : List[Any] =resid_pdrop SCREAMING_SNAKE_CASE__ : List[Any] =embd_pdrop SCREAMING_SNAKE_CASE__ : List[str] =attn_pdrop SCREAMING_SNAKE_CASE__ : Dict =layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =scale_attn_weights SCREAMING_SNAKE_CASE__ : Union[str, Any] =use_cache SCREAMING_SNAKE_CASE__ : Dict =attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : int =scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Dict =multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] =eos_token_id super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase )
665
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = JukeboxTokenizer snake_case_ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __magic_name__ ( self : Optional[int] ) -> str: import torch SCREAMING_SNAKE_CASE__ : List[str] =JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) SCREAMING_SNAKE_CASE__ : str =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : str =[ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __magic_name__ ( self : Any ) -> List[str]: import torch SCREAMING_SNAKE_CASE__ : int =JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer(**self.metas )['''input_ids'''] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] =[ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
665
1
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available a_ = logging.getLogger(__name__) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = 42 snake_case_ = 42 @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = 42 snake_case_ = None snake_case_ = None class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """train""" snake_case_ = """dev""" snake_case_ = """test""" class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( __lowercase : Union[str, Any] , __lowercase : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __magic_name__ ( __lowercase : str ) -> List[str]: raise NotImplementedError @staticmethod def __magic_name__ ( __lowercase : List[InputExample] , __lowercase : List[str] , __lowercase : int , __lowercase : PreTrainedTokenizer , __lowercase : Union[str, Any]=False , __lowercase : str="[CLS]" , __lowercase : List[str]=1 , __lowercase : Any="[SEP]" , __lowercase : Optional[Any]=False , __lowercase : Optional[Any]=False , __lowercase : Tuple=0 , __lowercase : Optional[int]=0 , __lowercase : List[str]=-1_00 , __lowercase : List[Any]=0 , __lowercase : List[Any]=True , ) -> List[InputFeatures]: SCREAMING_SNAKE_CASE__ : Any ={label: i for i, label in enumerate(__lowercase )} SCREAMING_SNAKE_CASE__ : Any =[] for ex_index, example in enumerate(__lowercase ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , __lowercase , len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] =[] SCREAMING_SNAKE_CASE__ : str =[] for word, label in zip(example.words , example.labels ): SCREAMING_SNAKE_CASE__ : int =tokenizer.tokenize(__lowercase ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__lowercase ) > 0: tokens.extend(__lowercase ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__lowercase ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.num_special_tokens_to_add() if len(__lowercase ) > max_seq_length - special_tokens_count: SCREAMING_SNAKE_CASE__ : List[Any] =tokens[: (max_seq_length - special_tokens_count)] SCREAMING_SNAKE_CASE__ : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] SCREAMING_SNAKE_CASE__ : List[str] =[sequence_a_segment_id] * len(__lowercase ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =[cls_token] + tokens SCREAMING_SNAKE_CASE__ : List[Any] =[pad_token_label_id] + label_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] =[cls_token_segment_id] + segment_ids SCREAMING_SNAKE_CASE__ : int =tokenizer.convert_tokens_to_ids(__lowercase ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. SCREAMING_SNAKE_CASE__ : Tuple =[1 if mask_padding_with_zero else 0] * len(__lowercase ) # Zero-pad up to the sequence length. SCREAMING_SNAKE_CASE__ : List[Any] =max_seq_length - len(__lowercase ) if pad_on_left: SCREAMING_SNAKE_CASE__ : Any =([pad_token] * padding_length) + input_ids SCREAMING_SNAKE_CASE__ : Tuple =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids SCREAMING_SNAKE_CASE__ : List[Any] =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__lowercase ) == max_seq_length assert len(__lowercase ) == max_seq_length assert len(__lowercase ) == max_seq_length assert len(__lowercase ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__lowercase ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__lowercase ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__lowercase ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__lowercase ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__lowercase ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: SCREAMING_SNAKE_CASE__ : Optional[Any] =None features.append( InputFeatures( input_ids=__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , label_ids=__lowercase ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = 42 snake_case_ = nn.CrossEntropyLoss().ignore_index def __init__( self : Union[str, Any] , __lowercase : TokenClassificationTask , __lowercase : str , __lowercase : PreTrainedTokenizer , __lowercase : List[str] , __lowercase : str , __lowercase : Optional[int] = None , __lowercase : Union[str, Any]=False , __lowercase : Split = Split.train , ) -> Dict: # Load data features from cache or dataset file SCREAMING_SNAKE_CASE__ : str =os.path.join( __lowercase , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__lowercase ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE__ : List[str] =cached_features_file + '''.lock''' with FileLock(__lowercase ): if os.path.exists(__lowercase ) and not overwrite_cache: logger.info(F"Loading features from cached file {cached_features_file}" ) SCREAMING_SNAKE_CASE__ : Dict =torch.load(__lowercase ) else: logger.info(F"Creating features from dataset file at {data_dir}" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =token_classification_task.read_examples_from_file(__lowercase , __lowercase ) # TODO clean up all this to leverage built-in features of tokenizers SCREAMING_SNAKE_CASE__ : Tuple =token_classification_task.convert_examples_to_features( __lowercase , __lowercase , __lowercase , __lowercase , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__lowercase , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F"Saving features into cached file {cached_features_file}" ) torch.save(self.features , __lowercase ) def __len__( self : Optional[Any] ) -> Tuple: return len(self.features ) def __getitem__( self : str , __lowercase : List[str] ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = -100 def __init__( self : Union[str, Any] , __lowercase : TokenClassificationTask , __lowercase : str , __lowercase : PreTrainedTokenizer , __lowercase : List[str] , __lowercase : str , __lowercase : Optional[int] = None , __lowercase : List[str]=False , __lowercase : Split = Split.train , ) -> str: SCREAMING_SNAKE_CASE__ : Any =token_classification_task.read_examples_from_file(__lowercase , __lowercase ) # TODO clean up all this to leverage built-in features of tokenizers SCREAMING_SNAKE_CASE__ : Optional[int] =token_classification_task.convert_examples_to_features( __lowercase , __lowercase , __lowercase , __lowercase , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__lowercase , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: SCREAMING_SNAKE_CASE__ : Optional[int] =tf.data.Dataset.from_generator( __lowercase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =tf.data.Dataset.from_generator( __lowercase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __magic_name__ ( self : Optional[int] ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Any =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[str] ) -> Tuple: return len(self.features ) def __getitem__( self : List[Any] , __lowercase : Any ) -> InputFeatures: return self.features[i]
665
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = """gpt_neox""" def __init__( self : List[Any] , __lowercase : Union[str, Any]=5_04_32 , __lowercase : int=61_44 , __lowercase : Tuple=44 , __lowercase : List[str]=64 , __lowercase : str=2_45_76 , __lowercase : Dict="gelu" , __lowercase : Tuple=0.25 , __lowercase : Tuple=1_00_00 , __lowercase : Tuple=0.0 , __lowercase : str=0.0 , __lowercase : List[Any]=0.1 , __lowercase : Dict=20_48 , __lowercase : Any=0.02 , __lowercase : Dict=1e-5 , __lowercase : List[Any]=True , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=False , __lowercase : List[Any]=True , __lowercase : Optional[Any]=None , **__lowercase : Any , ) -> Dict: super().__init__(bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Any =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : Any =num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_act SCREAMING_SNAKE_CASE__ : str =rotary_pct SCREAMING_SNAKE_CASE__ : Optional[Any] =rotary_emb_base SCREAMING_SNAKE_CASE__ : List[Any] =attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] =hidden_dropout SCREAMING_SNAKE_CASE__ : str =classifier_dropout SCREAMING_SNAKE_CASE__ : Any =initializer_range SCREAMING_SNAKE_CASE__ : Dict =layer_norm_eps SCREAMING_SNAKE_CASE__ : Any =use_cache SCREAMING_SNAKE_CASE__ : Tuple =tie_word_embeddings SCREAMING_SNAKE_CASE__ : Tuple =use_parallel_residual SCREAMING_SNAKE_CASE__ : Union[str, Any] =rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __lowercase ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"got {self.rope_scaling}" ) SCREAMING_SNAKE_CASE__ : int =self.rope_scaling.get('''type''' , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.rope_scaling.get('''factor''' , __lowercase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(__lowercase , __lowercase ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
665
1
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def _a( UpperCamelCase__ : str ): '''simple docstring''' if hor == 1_2_8: SCREAMING_SNAKE_CASE__ : List[Any] =('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') SCREAMING_SNAKE_CASE__ : Dict =(3_2, 1_2_8, 2_5_6) SCREAMING_SNAKE_CASE__ : List[str] =('''UpResnetBlock1D''', '''UpResnetBlock1D''') elif hor == 3_2: SCREAMING_SNAKE_CASE__ : Tuple =('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') SCREAMING_SNAKE_CASE__ : int =(3_2, 6_4, 1_2_8, 2_5_6) SCREAMING_SNAKE_CASE__ : Optional[Any] =('''UpResnetBlock1D''', '''UpResnetBlock1D''', '''UpResnetBlock1D''') SCREAMING_SNAKE_CASE__ : Union[str, Any] =torch.load(f"/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch" ) SCREAMING_SNAKE_CASE__ : int =model.state_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] ={ '''down_block_types''': down_block_types, '''block_out_channels''': block_out_channels, '''up_block_types''': up_block_types, '''layers_per_block''': 1, '''use_timestep_embedding''': True, '''out_block_type''': '''OutConv1DBlock''', '''norm_num_groups''': 8, '''downsample_each_block''': False, '''in_channels''': 1_4, '''out_channels''': 1_4, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''sample_size''': 6_5_5_3_6, '''mid_block_type''': '''MidResTemporalBlock1D''', '''act_fn''': '''mish''', } SCREAMING_SNAKE_CASE__ : Optional[int] =UNetaDModel(**UpperCamelCase__ ) print(f"length of state dict: {len(state_dict.keys() )}" ) print(f"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) SCREAMING_SNAKE_CASE__ : Tuple =dict(zip(model.state_dict().keys(), hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): SCREAMING_SNAKE_CASE__ : Any =state_dict.pop(UpperCamelCase__ ) hf_value_function.load_state_dict(UpperCamelCase__ ) torch.save(hf_value_function.state_dict(), f"hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin" ) with open(f"hub/hopper-medium-v2/unet/hor{hor}/config.json", '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str ={ '''in_channels''': 1_4, '''down_block_types''': ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''), '''up_block_types''': (), '''out_block_type''': '''ValueFunction''', '''mid_block_type''': '''ValueFunctionMidBlock1D''', '''block_out_channels''': (3_2, 6_4, 1_2_8, 2_5_6), '''layers_per_block''': 1, '''downsample_each_block''': True, '''sample_size''': 6_5_5_3_6, '''out_channels''': 1_4, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''use_timestep_embedding''': True, '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''norm_num_groups''': 8, '''act_fn''': '''mish''', } SCREAMING_SNAKE_CASE__ : Dict =torch.load('''/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model SCREAMING_SNAKE_CASE__ : int =UNetaDModel(**UpperCamelCase__ ) print(f"length of state dict: {len(state_dict.keys() )}" ) print(f"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) SCREAMING_SNAKE_CASE__ : Optional[int] =dict(zip(state_dict.keys(), hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): SCREAMING_SNAKE_CASE__ : Dict =state_dict.pop(UpperCamelCase__ ) hf_value_function.load_state_dict(UpperCamelCase__ ) torch.save(hf_value_function.state_dict(), '''hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin''' ) with open('''hub/hopper-medium-v2/value_function/config.json''', '''w''' ) as f: json.dump(UpperCamelCase__, UpperCamelCase__ ) if __name__ == "__main__": unet(3_2) # unet(128) value_function()
665
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
1
'''simple docstring''' import qiskit def _a( UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =qiskit.Aer.get_backend('''aer_simulator''' ) SCREAMING_SNAKE_CASE__ : List[Any] =qiskit.QuantumCircuit(4, 2 ) # encode inputs in qubits 0 and 1 if bita == 1: qc_ha.x(0 ) if bita == 1: qc_ha.x(1 ) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2 ) qc_ha.cx(1, 2 ) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3 ) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0 ) # extract XOR value qc_ha.measure(3, 1 ) # extract AND value # Execute the circuit on the qasm simulator SCREAMING_SNAKE_CASE__ : List[str] =qiskit.execute(UpperCamelCase__, UpperCamelCase__, shots=1_0_0_0 ) # Return the histogram data of the results of the experiment return job.result().get_counts(UpperCamelCase__ ) if __name__ == "__main__": a_ = half_adder(1, 1) print(F'''Half Adder Output Qubit Counts: {counts}''')
665
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Any =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(UpperCamelCase__ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : str =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(UpperCamelCase__ ) if len(UpperCamelCase__ ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(UpperCamelCase__ )} and {rowsa}" ) raise ValueError(UpperCamelCase__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any =table.shape strictly_diagonally_dominant(UpperCamelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for col in range(UpperCamelCase__ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : int =(temp + val) / denom new_val.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =new_val return [float(UpperCamelCase__ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Any =True for i in range(0, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
1