code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class snake_case__ ( unittest.TestCase ): A__ = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING A__ = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def A_ ( self : Optional[int] , __a : int , __a : List[Any] , __a : List[str] ) -> str: '''simple docstring''' __snake_case : Tuple = AudioClassificationPipeline(model=__a , feature_extractor=__a ) # test with a raw waveform __snake_case : List[Any] = np.zeros((34000,) ) __snake_case : Union[str, Any] = np.zeros((14000,) ) return audio_classifier, [audioa, audio] def A_ ( self : Any , __a : Any , __a : Tuple ) -> int: '''simple docstring''' __snake_case , __snake_case : Tuple = examples __snake_case : Optional[int] = audio_classifier(__a ) # by default a model is initialized with num_labels=2 self.assertEqual( __a , [ {'score': ANY(__a ), 'label': ANY(__a )}, {'score': ANY(__a ), 'label': ANY(__a )}, ] , ) __snake_case : Optional[Any] = audio_classifier(__a , top_k=1 ) self.assertEqual( __a , [ {'score': ANY(__a ), 'label': ANY(__a )}, ] , ) self.run_torchaudio(__a ) @require_torchaudio def A_ ( self : Optional[Any] , __a : str ) -> str: '''simple docstring''' import datasets # test with a local file __snake_case : Any = datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) __snake_case : Tuple = dataset[0]['audio']['array'] __snake_case : Any = audio_classifier(__a ) self.assertEqual( __a , [ {'score': ANY(__a ), 'label': ANY(__a )}, {'score': ANY(__a ), 'label': ANY(__a )}, ] , ) @require_torch def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' __snake_case : Any = 'anton-l/wav2vec2-random-tiny-classifier' __snake_case : List[Any] = pipeline('audio-classification' , model=__a ) __snake_case : Optional[Any] = np.ones((8000,) ) __snake_case : Any = audio_classifier(__a , top_k=4 ) __snake_case : Tuple = [ {'score': 0.0_8_4_2, 'label': 'no'}, {'score': 0.0_8_3_8, 'label': 'up'}, {'score': 0.0_8_3_7, 'label': 'go'}, {'score': 0.0_8_3_4, 'label': 'right'}, ] __snake_case : int = [ {'score': 0.0_8_4_5, 'label': 'stop'}, {'score': 0.0_8_4_4, 'label': 'on'}, {'score': 0.0_8_4_1, 'label': 'right'}, {'score': 0.0_8_3_4, 'label': 'left'}, ] self.assertIn(nested_simplify(__a , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) __snake_case : Any = {'array': np.ones((8000,) ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate} __snake_case : str = audio_classifier(__a , top_k=4 ) self.assertIn(nested_simplify(__a , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' import datasets __snake_case : int = 'superb/wav2vec2-base-superb-ks' __snake_case : Optional[int] = pipeline('audio-classification' , model=__a ) __snake_case : str = datasets.load_dataset('anton-l/superb_dummy' , 'ks' , split='test' ) __snake_case : int = np.array(dataset[3]['speech'] , dtype=np.floataa ) __snake_case : Tuple = audio_classifier(__a , top_k=4 ) self.assertEqual( nested_simplify(__a , decimals=3 ) , [ {'score': 0.9_8_1, 'label': 'go'}, {'score': 0.0_0_7, 'label': 'up'}, {'score': 0.0_0_6, 'label': '_unknown_'}, {'score': 0.0_0_1, 'label': 'down'}, ] , ) @require_tf @unittest.skip('Audio classification is not implemented for TF' ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' pass
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class snake_case__ : def __init__( self : List[Any] , __a : Any , __a : Dict , __a : bool = True , __a : bool = False ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = scheduler __snake_case : List[Any] = optimizers if isinstance(__a , (list, tuple) ) else [optimizers] __snake_case : List[Any] = split_batches __snake_case : str = step_with_optimizer __snake_case : int = GradientState() def A_ ( self : Optional[Any] , *__a : Tuple , **__a : Optional[Any] ) -> str: '''simple docstring''' if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__a , **__a ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__a , **__a ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step __snake_case : Dict = AcceleratorState().num_processes for _ in range(__a ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__a , **__a ) else: self.scheduler.step(*__a , **__a ) def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return self.scheduler.get_last_lr() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' return self.scheduler.state_dict() def A_ ( self : List[str] , __a : List[str] ) -> Optional[int]: '''simple docstring''' self.scheduler.load_state_dict(__a ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return self.scheduler.get_lr() def A_ ( self : str , *__a : Union[str, Any] , **__a : int ) -> List[str]: '''simple docstring''' return self.scheduler.print_lr(*__a , **__a )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' def a_ ( ) -> str: __snake_case : Optional[int] = 0 for i in range(1 ,10_01 ): total += i**i return str(_UpperCAmelCase )[-10:] if __name__ == "__main__": print(solution())
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class snake_case__ : def __init__( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = '' __snake_case : Optional[int] = '' __snake_case : Union[str, Any] = [] __snake_case : Dict = 0 __snake_case : Tuple = 256 __snake_case : Optional[int] = 0 __snake_case : Optional[Any] = 0 __snake_case : Optional[int] = 0 __snake_case : Dict = 0 def A_ ( self : Union[str, Any] , __a : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = cva.imread(__a , 0 ) __snake_case : Dict = copy.deepcopy(self.img ) __snake_case , __snake_case , __snake_case : Union[str, Any] = plt.hist(self.img.ravel() , 256 , [0, 256] , label='x' ) __snake_case : Optional[int] = np.sum(__a ) for i in range(len(__a ) ): __snake_case : Optional[Any] = x[i] / self.k self.sk += prk __snake_case : Any = (self.L - 1) * self.sk if self.rem != 0: __snake_case : List[str] = int(last % last ) __snake_case : Optional[int] = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__a ) __snake_case : Tuple = int(np.ma.count(self.img ) / self.img[1].size ) __snake_case : int = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): __snake_case : int = self.img[j][i] if num != self.last_list[num]: __snake_case : Tuple = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' plt.hist(self.img.ravel() , 256 , [0, 256] ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": A__ : Union[str, Any] = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') A__ : Any = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''char''' A__ = '''bpe''' A__ = '''wp''' A__ : List[Any] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = ['''image_processor''', '''char_tokenizer'''] A__ = '''ViTImageProcessor''' A__ = '''MgpstrTokenizer''' def __init__( self : Any , __a : Dict=None , __a : Dict=None , **__a : Any ) -> Dict: '''simple docstring''' __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.' , __a , ) __snake_case : Any = kwargs.pop('feature_extractor' ) __snake_case : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __snake_case : List[Any] = tokenizer __snake_case : List[str] = AutoTokenizer.from_pretrained('gpt2' ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(__a , __a ) def __call__( self : Tuple , __a : Dict=None , __a : int=None , __a : Dict=None , **__a : List[str] ) -> Any: '''simple docstring''' if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __snake_case : Optional[int] = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None: __snake_case : int = self.char_tokenizer(__a , return_tensors=__a , **__a ) if text is None: return inputs elif images is None: return encodings else: __snake_case : Optional[int] = encodings['input_ids'] return inputs def A_ ( self : Tuple , __a : str ) -> List[str]: '''simple docstring''' __snake_case , __snake_case , __snake_case : Union[str, Any] = sequences __snake_case : List[Any] = char_preds.size(0 ) __snake_case , __snake_case : Union[str, Any] = self._decode_helper(__a , 'char' ) __snake_case , __snake_case : Optional[int] = self._decode_helper(__a , 'bpe' ) __snake_case , __snake_case : Any = self._decode_helper(__a , 'wp' ) __snake_case : int = [] __snake_case : Tuple = [] for i in range(__a ): __snake_case : Tuple = [char_scores[i], bpe_scores[i], wp_scores[i]] __snake_case : List[str] = [char_strs[i], bpe_strs[i], wp_strs[i]] __snake_case : Optional[int] = scores.index(max(__a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __snake_case : Optional[Any] = {} __snake_case : int = final_strs __snake_case : Dict = final_scores __snake_case : int = char_strs __snake_case : Dict = bpe_strs __snake_case : Optional[Any] = wp_strs return out def A_ ( self : int , __a : Optional[int] , __a : Union[str, Any] ) -> Any: '''simple docstring''' if format == DecodeType.CHARACTER: __snake_case : Dict = self.char_decode __snake_case : Dict = 1 __snake_case : Optional[int] = '[s]' elif format == DecodeType.BPE: __snake_case : Any = self.bpe_decode __snake_case : Dict = 2 __snake_case : Any = '#' elif format == DecodeType.WORDPIECE: __snake_case : Tuple = self.wp_decode __snake_case : Optional[int] = 102 __snake_case : List[Any] = '[SEP]' else: raise ValueError(f'''Format {format} is not supported.''' ) __snake_case , __snake_case : Optional[int] = [], [] __snake_case : List[Any] = pred_logits.size(0 ) __snake_case : List[str] = pred_logits.size(1 ) __snake_case , __snake_case : Tuple = pred_logits.topk(1 , dim=-1 , largest=__a , sorted=__a ) __snake_case : Any = preds_index.view(-1 , __a )[:, 1:] __snake_case : Optional[int] = decoder(__a ) __snake_case , __snake_case : Optional[int] = torch.nn.functional.softmax(__a , dim=2 ).max(dim=2 ) __snake_case : Dict = preds_max_prob[:, 1:] for index in range(__a ): __snake_case : Optional[int] = preds_str[index].find(__a ) __snake_case : str = preds_str[index][:pred_eos] __snake_case : Any = preds_index[index].cpu().tolist() __snake_case : Any = pred_index.index(__a ) if eos_token in pred_index else -1 __snake_case : Any = preds_max_prob[index][: pred_eos_index + 1] __snake_case : Tuple = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__a ) conf_scores.append(__a ) return dec_strs, conf_scores def A_ ( self : int , __a : Dict ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(__a )] return decode_strs def A_ ( self : Dict , __a : List[str] ) -> Union[str, Any]: '''simple docstring''' return self.bpe_tokenizer.batch_decode(__a ) def A_ ( self : List[str] , __a : List[Any] ) -> Any: '''simple docstring''' __snake_case : List[str] = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(__a )] return decode_strs
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : str = logging.get_logger(__name__) A__ : Tuple = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''informer''' A__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[Any] , __a : Optional[int] = None , __a : Optional[int] = None , __a : str = "student_t" , __a : str = "nll" , __a : int = 1 , __a : List[int] = None , __a : Optional[Union[str, bool]] = "mean" , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : Optional[List[int]] = None , __a : Optional[List[int]] = None , __a : int = 64 , __a : int = 32 , __a : int = 32 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : bool = True , __a : str = "gelu" , __a : float = 0.0_5 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : int = 100 , __a : float = 0.0_2 , __a : Any=True , __a : str = "prob" , __a : int = 5 , __a : bool = True , **__a : int , ) -> List[Any]: '''simple docstring''' # time series specific configuration __snake_case : Any = prediction_length __snake_case : Union[str, Any] = context_length or prediction_length __snake_case : Dict = distribution_output __snake_case : Any = loss __snake_case : Tuple = input_size __snake_case : int = num_time_features __snake_case : Optional[Any] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __snake_case : List[str] = scaling __snake_case : List[str] = num_dynamic_real_features __snake_case : int = num_static_real_features __snake_case : List[Any] = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __snake_case : List[str] = cardinality else: __snake_case : Tuple = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __snake_case : Dict = embedding_dimension else: __snake_case : Optional[Any] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __snake_case : Union[str, Any] = num_parallel_samples # Transformer architecture configuration __snake_case : int = input_size * len(self.lags_sequence ) + self._number_of_features __snake_case : Tuple = d_model __snake_case : Dict = encoder_attention_heads __snake_case : Any = decoder_attention_heads __snake_case : Optional[Any] = encoder_ffn_dim __snake_case : Dict = decoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Dict = decoder_layers __snake_case : str = dropout __snake_case : Any = attention_dropout __snake_case : int = activation_dropout __snake_case : Optional[int] = encoder_layerdrop __snake_case : List[Any] = decoder_layerdrop __snake_case : Optional[Any] = activation_function __snake_case : Optional[int] = init_std __snake_case : str = use_cache # Informer __snake_case : List[Any] = attention_type __snake_case : Union[str, Any] = sampling_factor __snake_case : List[str] = distil super().__init__(is_encoder_decoder=__a , **__a ) @property def A_ ( self : int ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __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 ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( _UpperCAmelCase : Tuple ) -> Union[str, Any]: __snake_case , __snake_case : Any = image.size __snake_case , __snake_case : Optional[int] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __snake_case : int = image.resize((w, h) ,resample=PIL_INTERPOLATION['lanczos'] ) __snake_case : Dict = np.array(_UpperCAmelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Tuple = image[None].transpose(0 ,3 ,1 ,2 ) __snake_case : int = torch.from_numpy(_UpperCAmelCase ) return 2.0 * image - 1.0 class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : List[str] , __a : VQModel , __a : UNetaDModel , __a : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> List[str]: '''simple docstring''' super().__init__() self.register_modules(vqvae=__a , unet=__a , scheduler=__a ) @torch.no_grad() def __call__( self : Tuple , __a : Union[torch.Tensor, PIL.Image.Image] = None , __a : Optional[int] = 1 , __a : Optional[int] = 100 , __a : Optional[float] = 0.0 , __a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __a : Optional[str] = "pil" , __a : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(__a , PIL.Image.Image ): __snake_case : Union[str, Any] = 1 elif isinstance(__a , torch.Tensor ): __snake_case : str = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(__a )}''' ) if isinstance(__a , PIL.Image.Image ): __snake_case : Tuple = preprocess(__a ) __snake_case , __snake_case : Any = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : Dict = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : Optional[int] = next(self.unet.parameters() ).dtype __snake_case : int = randn_tensor(__a , generator=__a , device=self.device , dtype=__a ) __snake_case : Union[str, Any] = image.to(device=self.device , dtype=__a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(__a , device=self.device ) __snake_case : List[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Optional[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : str = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : str = {} if accepts_eta: __snake_case : Optional[Any] = eta for t in self.progress_bar(__a ): # concat latents and low resolution image in the channel dimension. __snake_case : int = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[int] = self.scheduler.scale_model_input(__a , __a ) # predict the noise residual __snake_case : List[str] = self.unet(__a , __a ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : List[Any] = self.scheduler.step(__a , __a , __a , **__a ).prev_sample # decode the image latents with the VQVAE __snake_case : Any = self.vqvae.decode(__a ).sample __snake_case : List[Any] = torch.clamp(__a , -1.0 , 1.0 ) __snake_case : Union[str, Any] = image / 2 + 0.5 __snake_case : str = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : str = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class snake_case__ : def __init__( self : List[str] ) -> None: '''simple docstring''' __snake_case : list[Any] = [] __snake_case : int = 0 __snake_case : int = 0 def A_ ( self : Tuple ) -> bool: '''simple docstring''' return self.head == self.tail def A_ ( self : int , __a : Any ) -> None: '''simple docstring''' self.data.append(__a ) __snake_case : Optional[int] = self.tail + 1 def A_ ( self : Dict ) -> Any: '''simple docstring''' __snake_case : Any = self.data[self.head] __snake_case : Dict = self.head + 1 return ret def A_ ( self : List[str] ) -> int: '''simple docstring''' return self.tail - self.head def A_ ( self : Union[str, Any] ) -> None: '''simple docstring''' print(self.data ) print('**************' ) print(self.data[self.head : self.tail] ) class snake_case__ : def __init__( self : List[Any] , __a : Any ) -> None: '''simple docstring''' __snake_case : List[str] = data __snake_case : MyNode | None = None __snake_case : MyNode | None = None __snake_case : int = 1 def A_ ( self : Dict ) -> Any: '''simple docstring''' return self.data def A_ ( self : List[str] ) -> MyNode | None: '''simple docstring''' return self.left def A_ ( self : Optional[Any] ) -> MyNode | None: '''simple docstring''' return self.right def A_ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.height def A_ ( self : Tuple , __a : Any ) -> None: '''simple docstring''' __snake_case : Dict = data def A_ ( self : List[str] , __a : MyNode | None ) -> None: '''simple docstring''' __snake_case : List[str] = node def A_ ( self : str , __a : MyNode | None ) -> None: '''simple docstring''' __snake_case : int = node def A_ ( self : Tuple , __a : int ) -> None: '''simple docstring''' __snake_case : Tuple = height def a_ ( _UpperCAmelCase : MyNode | None ) -> int: if node is None: return 0 return node.get_height() def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: if a > b: return a return b def a_ ( _UpperCAmelCase : MyNode ) -> MyNode: print('left rotation node:' ,node.get_data() ) __snake_case : Any = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(_UpperCAmelCase ) __snake_case : Optional[int] = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(_UpperCAmelCase ) __snake_case : Optional[Any] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(_UpperCAmelCase ) return ret def a_ ( _UpperCAmelCase : MyNode ) -> MyNode: print('right rotation node:' ,node.get_data() ) __snake_case : Dict = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(_UpperCAmelCase ) __snake_case : Union[str, Any] = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(_UpperCAmelCase ) __snake_case : List[str] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(_UpperCAmelCase ) return ret def a_ ( _UpperCAmelCase : MyNode ) -> MyNode: __snake_case : str = node.get_left() assert left_child is not None node.set_left(left_rotation(_UpperCAmelCase ) ) return right_rotation(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : MyNode ) -> MyNode: __snake_case : int = node.get_right() assert right_child is not None node.set_right(right_rotation(_UpperCAmelCase ) ) return left_rotation(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : MyNode | None ,_UpperCAmelCase : Any ) -> MyNode | None: if node is None: return MyNode(_UpperCAmelCase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() ,_UpperCAmelCase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected __snake_case : List[str] = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child __snake_case : Any = right_rotation(_UpperCAmelCase ) else: __snake_case : List[Any] = lr_rotation(_UpperCAmelCase ) else: node.set_right(insert_node(node.get_right() ,_UpperCAmelCase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: __snake_case : Dict = node.get_right() assert right_child is not None if data < right_child.get_data(): __snake_case : Tuple = rl_rotation(_UpperCAmelCase ) else: __snake_case : int = left_rotation(_UpperCAmelCase ) __snake_case : Optional[Any] = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(_UpperCAmelCase ) return node def a_ ( _UpperCAmelCase : MyNode ) -> Any: while True: __snake_case : int = root.get_right() if right_child is None: break __snake_case : int = right_child return root.get_data() def a_ ( _UpperCAmelCase : MyNode ) -> Any: while True: __snake_case : List[Any] = root.get_left() if left_child is None: break __snake_case : List[str] = left_child return root.get_data() def a_ ( _UpperCAmelCase : MyNode ,_UpperCAmelCase : Any ) -> MyNode | None: __snake_case : Tuple = root.get_left() __snake_case : int = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: __snake_case : Any = get_left_most(_UpperCAmelCase ) root.set_data(_UpperCAmelCase ) root.set_right(del_node(_UpperCAmelCase ,_UpperCAmelCase ) ) elif left_child is not None: __snake_case : Tuple = left_child elif right_child is not None: __snake_case : str = right_child else: return None elif root.get_data() > data: if left_child is None: print('No such data' ) return root else: root.set_left(del_node(_UpperCAmelCase ,_UpperCAmelCase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(_UpperCAmelCase ,_UpperCAmelCase ) ) if get_height(_UpperCAmelCase ) - get_height(_UpperCAmelCase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): __snake_case : List[Any] = left_rotation(_UpperCAmelCase ) else: __snake_case : Tuple = rl_rotation(_UpperCAmelCase ) elif get_height(_UpperCAmelCase ) - get_height(_UpperCAmelCase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): __snake_case : List[Any] = right_rotation(_UpperCAmelCase ) else: __snake_case : Any = lr_rotation(_UpperCAmelCase ) __snake_case : List[str] = my_max(get_height(root.get_right() ) ,get_height(root.get_left() ) ) + 1 root.set_height(_UpperCAmelCase ) return root class snake_case__ : def __init__( self : Dict ) -> None: '''simple docstring''' __snake_case : MyNode | None = None def A_ ( self : str ) -> int: '''simple docstring''' return get_height(self.root ) def A_ ( self : List[str] , __a : Any ) -> None: '''simple docstring''' print('insert:' + str(__a ) ) __snake_case : Optional[Any] = insert_node(self.root , __a ) def A_ ( self : Union[str, Any] , __a : Any ) -> None: '''simple docstring''' print('delete:' + str(__a ) ) if self.root is None: print('Tree is empty!' ) return __snake_case : Optional[Any] = del_node(self.root , __a ) def __str__( self : Optional[Any] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' __snake_case : Union[str, Any] = '' __snake_case : List[Any] = MyQueue() q.push(self.root ) __snake_case : Dict = self.get_height() if layer == 0: return output __snake_case : Any = 0 while not q.is_empty(): __snake_case : List[str] = q.pop() __snake_case : List[Any] = ' ' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(__a ) q.push(__a ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space __snake_case : Dict = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , __a ) - 1: __snake_case : Union[str, Any] = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def a_ ( ) -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() A__ : Optional[Any] = AVLtree() A__ : Optional[Any] = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
1
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
1
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> bool: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False __snake_case : Dict = range(3 ,int(math.sqrt(_UpperCAmelCase ) + 1 ) ,2 ) return not any(not number % i for i in odd_numbers ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : List[str]=1 ,**_UpperCAmelCase : List[Any] ) -> int: __snake_case : Union[str, Any] = factor * value __snake_case : List[Any] = value while not is_prime(_UpperCAmelCase ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 ,**_UpperCAmelCase ) return value
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
1
'''simple docstring''' from __future__ import annotations A__ : Optional[int] = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } class snake_case__ : def __init__( self : Tuple , __a : dict[str, list[str]] , __a : str ) -> None: '''simple docstring''' __snake_case : Optional[Any] = graph # mapping node to its parent in resulting breadth first tree __snake_case : dict[str, str | None] = {} __snake_case : Optional[int] = source_vertex def A_ ( self : Tuple ) -> None: '''simple docstring''' __snake_case : Union[str, Any] = {self.source_vertex} __snake_case : Any = None __snake_case : Union[str, Any] = [self.source_vertex] # first in first out queue while queue: __snake_case : str = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__a ) __snake_case : Tuple = vertex queue.append(__a ) def A_ ( self : Optional[int] , __a : str ) -> str: '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __snake_case : str = self.parent.get(__a ) if target_vertex_parent is None: __snake_case : Dict = ( f'''No path from vertex: {self.source_vertex} to vertex: {target_vertex}''' ) raise ValueError(__a ) return self.shortest_path(__a ) + f'''->{target_vertex}''' if __name__ == "__main__": A__ : Any = Graph(graph, '''G''') g.breath_first_search() print(g.shortest_path('''D''')) print(g.shortest_path('''G''')) print(g.shortest_path('''Foo'''))
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def a_ ( ) -> str: __snake_case : int = ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' ,type=_UpperCAmelCase ,default=1 ,help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' ,type=_UpperCAmelCase ,help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) ,) # rest from the training program parser.add_argument('training_script_args' ,nargs=_UpperCAmelCase ) return parser.parse_args() def a_ ( ) -> Any: __snake_case : Dict = parse_args() # Import training_script as a module. __snake_case : str = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) __snake_case : Any = script_fpath.stem __snake_case : Union[str, Any] = importlib.import_module(_UpperCAmelCase ) # Patch sys.argv __snake_case : Union[str, Any] = [args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn ,args=() ,nprocs=args.num_cores ) if __name__ == "__main__": main()
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1
'''simple docstring''' import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class snake_case__ ( unittest.TestCase ): def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Any = 'hf-internal-testing/tiny-random-t5' __snake_case : List[Any] = AutoTokenizer.from_pretrained(__a ) __snake_case : Any = AutoModelForSeqaSeqLM.from_pretrained(__a ) __snake_case : str = tokenizer('This is me' , return_tensors='pt' ) __snake_case : Any = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __snake_case : Optional[int] = model.generate(**__a ) __snake_case : List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__a ) __snake_case : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__a ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __snake_case : int = model_reloaded.generate(**__a ) self.assertTrue(torch.allclose(__a , __a ) ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Any = 'hf-internal-testing/tiny-random-t5' __snake_case : int = AutoModelForSeqaSeqLM.from_pretrained(__a ) __snake_case : int = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__a ): model.save_pretrained(__a ) __snake_case : List[str] = model.reverse_bettertransformer() model.save_pretrained(__a )
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def a_ ( _UpperCAmelCase : Optional[int]=None ) -> Any: if subparsers is not None: __snake_case : Any = subparsers.add_parser('tpu-config' ,description=_description ) else: __snake_case : Union[str, Any] = argparse.ArgumentParser('Accelerate tpu-config command' ,description=_description ) # Core arguments __snake_case : Optional[Any] = parser.add_argument_group( 'Config Arguments' ,'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' ,type=_UpperCAmelCase ,default=_UpperCAmelCase ,help='Path to the config file to use for accelerate.' ,) config_args.add_argument( '--tpu_name' ,default=_UpperCAmelCase ,help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' ,) config_args.add_argument( '--tpu_zone' ,default=_UpperCAmelCase ,help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' ,) __snake_case : Union[str, Any] = parser.add_argument_group('TPU Arguments' ,'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' ,action='store_true' ,help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' ,) pod_args.add_argument( '--command_file' ,default=_UpperCAmelCase ,help='The path to the file containing the commands to run on the pod on startup.' ,) pod_args.add_argument( '--command' ,action='append' ,nargs='+' ,help='A command to run on the pod. Can be passed multiple times.' ,) pod_args.add_argument( '--install_accelerate' ,action='store_true' ,help='Whether to install accelerate on the pod. Defaults to False.' ,) pod_args.add_argument( '--accelerate_version' ,default='latest' ,help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' ,) pod_args.add_argument( '--debug' ,action='store_true' ,help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=_UpperCAmelCase ) return parser def a_ ( _UpperCAmelCase : Optional[Any] ) -> int: __snake_case : Dict = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(_UpperCAmelCase ): __snake_case : Union[str, Any] = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __snake_case : int = defaults.command_file if not args.command and defaults.commands is not None: __snake_case : Any = defaults.commands if not args.tpu_name: __snake_case : int = defaults.tpu_name if not args.tpu_zone: __snake_case : List[Any] = defaults.tpu_zone if args.accelerate_version == "dev": __snake_case : Optional[int] = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": __snake_case : Dict = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) ,_UpperCAmelCase ): __snake_case : Union[str, Any] = f'''accelerate=={args.accelerate_version}''' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file ,'r' ) as f: __snake_case : List[str] = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] ,_UpperCAmelCase ): __snake_case : Optional[int] = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __snake_case : Optional[Any] = ['cd /usr/share'] if args.install_accelerate: new_cmd += [f'''pip install {args.accelerate_version}'''] new_cmd += args.command __snake_case : Optional[Any] = '; '.join(_UpperCAmelCase ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __snake_case : Any = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f'''Running {" ".join(_UpperCAmelCase )}''' ) return subprocess.run(_UpperCAmelCase ) print('Successfully setup pod.' ) def a_ ( ) -> List[str]: __snake_case : Optional[Any] = tpu_command_parser() __snake_case : Optional[int] = parser.parse_args() tpu_command_launcher(_UpperCAmelCase )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
1
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
1
'''simple docstring''' import torch from diffusers import DiffusionPipeline class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Any , __a : Optional[Any] , __a : int ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules(unet=__a , scheduler=__a ) def __call__( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : str = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __snake_case : Tuple = 1 __snake_case : Optional[Any] = self.unet(__a , __a ).sample __snake_case : Any = self.scheduler.step(__a , __a , __a ).prev_sample __snake_case : str = scheduler_output - scheduler_output + torch.ones_like(__a ) return result
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __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 A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
'''simple docstring''' import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[str] ) -> List[str]: # Load configuration defined in the metadata file with open(_UpperCAmelCase ) as metadata_file: __snake_case : Optional[Any] = json.load(_UpperCAmelCase ) __snake_case : Optional[Any] = LukeConfig(use_entity_aware_attention=_UpperCAmelCase ,**metadata['model_config'] ) # Load in the weights from the checkpoint_path __snake_case : int = torch.load(_UpperCAmelCase ,map_location='cpu' ) # Load the entity vocab file __snake_case : Optional[int] = load_entity_vocab(_UpperCAmelCase ) __snake_case : Tuple = RobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks __snake_case : int = AddedToken('<ent>' ,lstrip=_UpperCAmelCase ,rstrip=_UpperCAmelCase ) __snake_case : str = 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 ,LukeTokenizer.vocab_files_names['entity_vocab_file'] ) ,'w' ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : Optional[int] = LukeTokenizer.from_pretrained(_UpperCAmelCase ) # Initialize the embeddings of the special tokens __snake_case : Dict = state_dict['embeddings.word_embeddings.weight'] __snake_case : List[str] = word_emb[tokenizer.convert_tokens_to_ids(['@'] )[0]].unsqueeze(0 ) __snake_case : str = word_emb[tokenizer.convert_tokens_to_ids(['#'] )[0]].unsqueeze(0 ) __snake_case : int = torch.cat([word_emb, ent_emb, enta_emb] ) # 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"]: __snake_case : Tuple = f'''encoder.layer.{layer_index}.attention.self.''' __snake_case : Optional[Any] = state_dict[prefix + matrix_name] __snake_case : List[Any] = state_dict[prefix + matrix_name] __snake_case : int = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __snake_case : Dict = state_dict['entity_embeddings.entity_embeddings.weight'] __snake_case : List[str] = entity_emb[entity_vocab['[MASK]']] __snake_case : int = LukeModel(config=_UpperCAmelCase ).eval() __snake_case , __snake_case : str = model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) if not (len(_UpperCAmelCase ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(f'''Missing keys {", ".join(_UpperCAmelCase )}. Expected only missing embeddings.position_ids''' ) if not (all(key.startswith('entity_predictions' ) or key.startswith('lm_head' ) for key in unexpected_keys )): raise ValueError( 'Unexpected keys' f''' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}''' ) # Check outputs __snake_case : Optional[Any] = LukeTokenizer.from_pretrained(_UpperCAmelCase ,task='entity_classification' ) __snake_case : List[Any] = ( 'Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the' ' new world number one avoid a humiliating second- round exit at Wimbledon .' ) __snake_case : str = (39, 42) __snake_case : str = tokenizer(_UpperCAmelCase ,entity_spans=[span] ,add_prefix_space=_UpperCAmelCase ,return_tensors='pt' ) __snake_case : Tuple = model(**_UpperCAmelCase ) # Verify word hidden states if model_size == "large": __snake_case : List[str] = torch.Size((1, 42, 10_24) ) __snake_case : Tuple = torch.tensor( [[0.0_1_3_3, 0.0_8_6_5, 0.0_0_9_5], [0.3_0_9_3, -0.2_5_7_6, -0.7_4_1_8], [-0.1_7_2_0, -0.2_1_1_7, -0.2_8_6_9]] ) else: # base __snake_case : List[str] = torch.Size((1, 42, 7_68) ) __snake_case : Union[str, Any] = torch.tensor([[0.0_0_3_7, 0.1_3_6_8, -0.0_0_9_1], [0.1_0_9_9, 0.3_3_2_9, -0.1_0_9_5], [0.0_7_6_5, 0.5_3_3_5, 0.1_1_7_9]] ) 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": __snake_case : Any = torch.Size((1, 1, 10_24) ) __snake_case : Optional[int] = torch.tensor([[0.0_4_6_6, -0.0_1_0_6, -0.0_1_7_9]] ) else: # base __snake_case : str = torch.Size((1, 1, 7_68) ) __snake_case : Tuple = torch.tensor([[0.1_4_5_7, 0.1_0_4_4, 0.0_1_7_4]] ) 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 # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(_UpperCAmelCase ) ) model.save_pretrained(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[Any] ) -> Any: __snake_case : List[str] = {} with open(_UpperCAmelCase ,'r' ,encoding='utf-8' ) as f: for index, line in enumerate(_UpperCAmelCase ): __snake_case , __snake_case : List[Any] = line.rstrip().split('\t' ) __snake_case : str = index return entity_vocab if __name__ == "__main__": A__ : Tuple = 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__ : str = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' from math import pi def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> float: return 2 * pi * radius * (angle / 3_60) if __name__ == "__main__": print(arc_length(9_0, 1_0))
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() A__ : List[str] = logging.get_logger(__name__) set_seed(7_7_0) A__ : Optional[Any] = { '''c_attn''': '''att_proj''', '''c_proj''': '''out_proj''', '''c_fc''': '''in_proj''', '''transformer.''': '''''', '''h.''': '''layers.''', '''ln_1''': '''layernorm_1''', '''ln_2''': '''layernorm_2''', '''ln_f''': '''layernorm_final''', '''wpe''': '''position_embeds_layer''', '''wte''': '''input_embeds_layer''', } A__ : Tuple = { '''text_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text.pt''', }, '''coarse_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse.pt''', }, '''fine_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine.pt''', }, '''text''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text_2.pt''', }, '''coarse''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse_2.pt''', }, '''fine''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine_2.pt''', }, } A__ : str = os.path.dirname(os.path.abspath(__file__)) A__ : Tuple = os.path.join(os.path.expanduser('''~'''), '''.cache''') A__ : List[Any] = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''') def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[str]=False ) -> int: __snake_case : int = model_type if use_small: key += "_small" return os.path.join(_UpperCAmelCase ,REMOTE_MODEL_PATHS[key]['file_name'] ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[str] ) -> Any: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) hf_hub_download(repo_id=_UpperCAmelCase ,filename=_UpperCAmelCase ,local_dir=_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : int=False ,_UpperCAmelCase : str="text" ) -> Optional[Any]: if model_type == "text": __snake_case : Tuple = BarkSemanticModel __snake_case : Optional[int] = BarkSemanticConfig __snake_case : str = BarkSemanticGenerationConfig elif model_type == "coarse": __snake_case : List[Any] = BarkCoarseModel __snake_case : Optional[int] = BarkCoarseConfig __snake_case : Optional[int] = BarkCoarseGenerationConfig elif model_type == "fine": __snake_case : List[Any] = BarkFineModel __snake_case : Union[str, Any] = BarkFineConfig __snake_case : Union[str, Any] = BarkFineGenerationConfig else: raise NotImplementedError() __snake_case : List[str] = f'''{model_type}_small''' if use_small else model_type __snake_case : Tuple = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(_UpperCAmelCase ): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info['repo_id'] ,model_info['file_name'] ) __snake_case : Union[str, Any] = torch.load(_UpperCAmelCase ,map_location=_UpperCAmelCase ) # this is a hack __snake_case : List[str] = checkpoint['model_args'] if "input_vocab_size" not in model_args: __snake_case : int = model_args['vocab_size'] __snake_case : List[str] = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments __snake_case : Union[str, Any] = model_args.pop('n_head' ) __snake_case : Dict = model_args.pop('n_embd' ) __snake_case : Any = model_args.pop('n_layer' ) __snake_case : Tuple = ConfigClass(**checkpoint['model_args'] ) __snake_case : List[Any] = ModelClass(config=_UpperCAmelCase ) __snake_case : Any = GenerationConfigClass() __snake_case : Tuple = model_generation_config __snake_case : Any = checkpoint['model'] # fixup checkpoint __snake_case : Union[str, Any] = '_orig_mod.' for k, v in list(state_dict.items() ): if k.startswith(_UpperCAmelCase ): # replace part of the key with corresponding layer name in HF implementation __snake_case : int = k[len(_UpperCAmelCase ) :] for old_layer_name in new_layer_name_dict: __snake_case : Dict = new_k.replace(_UpperCAmelCase ,new_layer_name_dict[old_layer_name] ) __snake_case : List[str] = state_dict.pop(_UpperCAmelCase ) __snake_case : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) __snake_case : Any = {k for k in extra_keys if not k.endswith('.attn.bias' )} __snake_case : str = set(model.state_dict().keys() ) - set(state_dict.keys() ) __snake_case : Any = {k for k in missing_keys if not k.endswith('.attn.bias' )} if len(_UpperCAmelCase ) != 0: raise ValueError(f'''extra keys found: {extra_keys}''' ) if len(_UpperCAmelCase ) != 0: raise ValueError(f'''missing keys: {missing_keys}''' ) model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) __snake_case : List[str] = model.num_parameters(exclude_embeddings=_UpperCAmelCase ) __snake_case : Optional[Any] = checkpoint['best_val_loss'].item() logger.info(f'''model loaded: {round(n_params/1E6 ,1 )}M params, {round(_UpperCAmelCase ,3 )} loss''' ) model.eval() model.to(_UpperCAmelCase ) del checkpoint, state_dict return model def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any]=False ,_UpperCAmelCase : Optional[int]="text" ) -> Union[str, Any]: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() __snake_case : int = 'cpu' # do conversion on cpu __snake_case : List[Any] = _get_ckpt_path(_UpperCAmelCase ,use_small=_UpperCAmelCase ) __snake_case : Any = _load_model(_UpperCAmelCase ,_UpperCAmelCase ,model_type=_UpperCAmelCase ,use_small=_UpperCAmelCase ) # load bark initial model __snake_case : Union[str, Any] = _bark_load_model(_UpperCAmelCase ,'cpu' ,model_type=_UpperCAmelCase ,use_small=_UpperCAmelCase ) if model_type == "text": __snake_case : Optional[int] = bark_model['model'] if model.num_parameters(exclude_embeddings=_UpperCAmelCase ) != bark_model.get_num_params(): raise ValueError('initial and new models don\'t have the same number of parameters' ) # check if same output as the bark model __snake_case : List[Any] = 5 __snake_case : str = 10 if model_type in ["text", "coarse"]: __snake_case : Tuple = torch.randint(2_56 ,(batch_size, sequence_length) ,dtype=torch.int ) __snake_case : Optional[int] = bark_model(_UpperCAmelCase )[0] __snake_case : List[str] = model(_UpperCAmelCase ) # take last logits __snake_case : List[Any] = output_new_model_total.logits[:, [-1], :] else: __snake_case : Optional[Any] = 3 __snake_case : List[Any] = 8 __snake_case : List[str] = torch.randint(2_56 ,(batch_size, sequence_length, n_codes_total) ,dtype=torch.int ) __snake_case : str = model(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : List[str] = bark_model(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('initial and new outputs don\'t have the same shape' ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError('initial and new outputs are not equal' ) Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : str ,_UpperCAmelCase : Any ,) -> int: __snake_case : int = os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : Dict = BarkSemanticConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : Dict = BarkCoarseConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : List[Any] = BarkFineConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : Dict = EncodecConfig.from_pretrained('facebook/encodec_24khz' ) __snake_case : List[Any] = BarkSemanticModel.from_pretrained(_UpperCAmelCase ) __snake_case : Dict = BarkCoarseModel.from_pretrained(_UpperCAmelCase ) __snake_case : Dict = BarkFineModel.from_pretrained(_UpperCAmelCase ) __snake_case : Any = EncodecModel.from_pretrained('facebook/encodec_24khz' ) __snake_case : Tuple = BarkConfig.from_sub_model_configs( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : List[str] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config ,coarseAcoustic.generation_config ,fineAcoustic.generation_config ) __snake_case : str = BarkModel(_UpperCAmelCase ) __snake_case : Tuple = semantic __snake_case : Any = coarseAcoustic __snake_case : Tuple = fineAcoustic __snake_case : Any = codec __snake_case : Optional[int] = bark_generation_config Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) bark.save_pretrained(_UpperCAmelCase ,repo_id=_UpperCAmelCase ,push_to_hub=_UpperCAmelCase ) if __name__ == "__main__": A__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''model_type''', type=str, help='''text, coarse or fine.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--is_small''', action='''store_true''', help='''convert the small version instead of the large.''') A__ : Dict = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
'''simple docstring''' import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class snake_case__ ( unittest.TestCase ): @parameterized.expand([(None,), ('foo.json',)] ) def A_ ( self : str , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Dict = GenerationConfig( do_sample=__a , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__a , config_name=__a ) __snake_case : Optional[int] = GenerationConfig.from_pretrained(__a , config_name=__a ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , __a ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , __a ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = AutoConfig.from_pretrained('gpt2' ) __snake_case : Optional[int] = GenerationConfig.from_model_config(__a ) __snake_case : str = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(__a , __a ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' __snake_case : Optional[int] = GenerationConfig() __snake_case : Any = { 'max_new_tokens': 1024, 'foo': 'bar', } __snake_case : Optional[Any] = copy.deepcopy(__a ) __snake_case : Tuple = generation_config.update(**__a ) # update_kwargs was not modified (no side effects) self.assertEqual(__a , __a ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(__a , {'foo': 'bar'} ) def A_ ( self : Dict ) -> str: '''simple docstring''' __snake_case : int = GenerationConfig() __snake_case : Tuple = 'bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(__a ) __snake_case : List[str] = GenerationConfig.from_pretrained(__a ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar' ) __snake_case : List[str] = GenerationConfig.from_model_config(__a ) assert not hasattr(__a , 'foo' ) # no new kwargs should be initialized if from config def A_ ( self : Tuple ) -> str: '''simple docstring''' __snake_case : List[Any] = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , __a ) self.assertEqual(default_config.num_beams , 1 ) __snake_case : List[Any] = GenerationConfig( do_sample=__a , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , __a ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__a ) __snake_case : List[str] = GenerationConfig.from_pretrained(__a , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , __a ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class snake_case__ ( unittest.TestCase ): @classmethod def A_ ( cls : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TOKEN HfFolder.save_token(__a ) @classmethod def A_ ( cls : Dict ) -> List[Any]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' __snake_case : Optional[Any] = GenerationConfig( do_sample=__a , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token ) __snake_case : str = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __a , repo_id='test-generation-config' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : List[str] = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) def A_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[int] = GenerationConfig( do_sample=__a , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token ) __snake_case : Dict = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __a , repo_id='valid_org/test-generation-config-org' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : Dict = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) )
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : List[Any] = { '''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 snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''markuplm''' def __init__( self : Optional[int] , __a : Union[str, Any]=30522 , __a : Any=768 , __a : Dict=12 , __a : Tuple=12 , __a : Optional[int]=3072 , __a : Optional[int]="gelu" , __a : Any=0.1 , __a : Any=0.1 , __a : Union[str, Any]=512 , __a : Any=2 , __a : List[str]=0.0_2 , __a : Optional[Any]=1e-12 , __a : List[str]=0 , __a : List[Any]=0 , __a : Optional[Any]=2 , __a : Optional[Any]=256 , __a : Any=1024 , __a : Tuple=216 , __a : List[str]=1001 , __a : Optional[int]=32 , __a : str=50 , __a : Tuple="absolute" , __a : Dict=True , __a : Tuple=None , **__a : List[Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a , ) __snake_case : str = vocab_size __snake_case : List[str] = hidden_size __snake_case : Optional[Any] = num_hidden_layers __snake_case : int = num_attention_heads __snake_case : List[Any] = hidden_act __snake_case : Any = intermediate_size __snake_case : Any = hidden_dropout_prob __snake_case : Union[str, Any] = attention_probs_dropout_prob __snake_case : List[Any] = max_position_embeddings __snake_case : str = type_vocab_size __snake_case : Any = initializer_range __snake_case : Tuple = layer_norm_eps __snake_case : str = position_embedding_type __snake_case : str = use_cache __snake_case : Union[str, Any] = classifier_dropout # additional properties __snake_case : List[str] = max_depth __snake_case : int = max_xpath_tag_unit_embeddings __snake_case : Dict = max_xpath_subs_unit_embeddings __snake_case : Any = tag_pad_id __snake_case : Optional[int] = subs_pad_id __snake_case : List[str] = xpath_unit_hidden_size
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
1
'''simple docstring''' from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str] = logging.get_logger(__name__) A__ : Optional[Any] = { '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''autoformer''' A__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Union[str, Any] , __a : Optional[int] = None , __a : Optional[int] = None , __a : str = "student_t" , __a : str = "nll" , __a : int = 1 , __a : List[int] = [1, 2, 3, 4, 5, 6, 7] , __a : bool = True , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : Optional[List[int]] = None , __a : Optional[List[int]] = None , __a : int = 64 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : int = 32 , __a : int = 32 , __a : str = "gelu" , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : int = 100 , __a : float = 0.0_2 , __a : bool = True , __a : int=True , __a : int = 10 , __a : int = 25 , __a : int = 3 , **__a : int , ) -> Optional[int]: '''simple docstring''' # time series specific configuration __snake_case : Optional[int] = prediction_length __snake_case : int = context_length if context_length is not None else prediction_length __snake_case : Any = distribution_output __snake_case : List[str] = loss __snake_case : List[Any] = input_size __snake_case : List[str] = num_time_features __snake_case : int = lags_sequence __snake_case : List[str] = scaling __snake_case : Optional[int] = num_dynamic_real_features __snake_case : Tuple = num_static_real_features __snake_case : str = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __snake_case : List[Any] = cardinality else: __snake_case : List[Any] = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __snake_case : int = embedding_dimension else: __snake_case : Optional[Any] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __snake_case : Any = num_parallel_samples # Transformer architecture configuration __snake_case : List[str] = input_size * len(self.lags_sequence ) + self._number_of_features __snake_case : Optional[int] = d_model __snake_case : List[Any] = encoder_attention_heads __snake_case : List[Any] = decoder_attention_heads __snake_case : Any = encoder_ffn_dim __snake_case : Optional[int] = decoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Any = decoder_layers __snake_case : List[str] = dropout __snake_case : Optional[int] = attention_dropout __snake_case : Optional[Any] = activation_dropout __snake_case : Optional[Any] = encoder_layerdrop __snake_case : List[Any] = decoder_layerdrop __snake_case : Optional[Any] = activation_function __snake_case : Tuple = init_std __snake_case : Optional[int] = use_cache # Autoformer __snake_case : List[str] = label_length __snake_case : Optional[int] = moving_average __snake_case : List[str] = autocorrelation_factor super().__init__(is_encoder_decoder=__a , **__a ) @property def A_ ( self : Optional[Any] ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
1
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : str = f'''Input value of [number={number}] must be an integer''' raise TypeError(_UpperCAmelCase ) if number < 0: return False __snake_case : Tuple = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A__ : int = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A__ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('''\n'''.join(upper_files) + '''\n''') A__ : Optional[Any] = [file for file in filepaths if ''' ''' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('''\n'''.join(space_files) + '''\n''') A__ : Optional[Any] = [file for file in filepaths if '''-''' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('''\n'''.join(hyphen_files) + '''\n''') A__ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('''\n'''.join(nodir_files) + '''\n''') A__ : List[Any] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def a_ ( ) -> str: __snake_case : str = 10 __snake_case : Tuple = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) __snake_case : str = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(_UpperCAmelCase ) ), } ,features=_UpperCAmelCase ,) return dataset @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Any = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=_UpperCAmelCase ) return filename # FILE_CONTENT + files A__ : Optional[int] = '''\ Text data. Second line of data.''' @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ) -> Union[str, Any]: __snake_case : int = tmp_path_factory.mktemp('data' ) / 'file.txt' __snake_case : Union[str, Any] = FILE_CONTENT with open(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ) return filename @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Dict ) -> Tuple: import bza __snake_case : Dict = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' __snake_case : Any = bytes(_UpperCAmelCase ,'utf-8' ) with bza.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : int ) -> str: import gzip __snake_case : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) __snake_case : Tuple = bytes(_UpperCAmelCase ,'utf-8' ) with gzip.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ) -> str: if datasets.config.LZ4_AVAILABLE: import lza.frame __snake_case : int = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' __snake_case : int = bytes(_UpperCAmelCase ,'utf-8' ) with lza.frame.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr __snake_case : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(_UpperCAmelCase ,'w' ) as archive: archive.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Dict ) -> str: import tarfile __snake_case : int = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(_UpperCAmelCase ,'w' ) as f: f.add(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ) -> str: import lzma __snake_case : List[str] = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' __snake_case : Tuple = bytes(_UpperCAmelCase ,'utf-8' ) with lzma.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ) -> Dict: import zipfile __snake_case : int = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ) -> Any: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd __snake_case : int = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' __snake_case : int = bytes(_UpperCAmelCase ,'utf-8' ) with zstd.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[int]: __snake_case : Tuple = tmp_path_factory.mktemp('data' ) / 'file.xml' __snake_case : str = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ) return filename A__ : List[Any] = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] A__ : Any = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] A__ : Union[str, Any] = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } A__ : int = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] A__ : Optional[Any] = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope='session' ) def a_ ( ) -> List[Any]: return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[str] ) -> Any: __snake_case : Any = datasets.Dataset.from_dict(_UpperCAmelCase ) __snake_case : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[Any] ) -> Optional[Any]: __snake_case : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: __snake_case : str = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' ,tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ) -> Optional[int]: __snake_case : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(_UpperCAmelCase ,'w' ,newline='' ) as f: __snake_case : Optional[int] = csv.DictWriter(_UpperCAmelCase ,fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ) -> Tuple: __snake_case : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(_UpperCAmelCase ,'w' ,newline='' ) as f: __snake_case : Optional[int] = csv.DictWriter(_UpperCAmelCase ,fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ) -> Optional[int]: import bza __snake_case : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(_UpperCAmelCase ,'rb' ) as f: __snake_case : List[Any] = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_UpperCAmelCase ,'wb' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ) -> Any: __snake_case : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ) -> Optional[int]: __snake_case : Dict = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(csv_path.replace('.csv' ,'.CSV' ) ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename(csva_path.replace('.csv' ,'.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str ,_UpperCAmelCase : Tuple ) -> List[str]: __snake_case : Optional[int] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : str ) -> Union[str, Any]: __snake_case : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) __snake_case : Union[str, Any] = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(_UpperCAmelCase ,'wb' ) as f: __snake_case : Union[str, Any] = pq.ParquetWriter(_UpperCAmelCase ,schema=_UpperCAmelCase ) __snake_case : Dict = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_UpperCAmelCase ) )] for k in DATA[0]} ,schema=_UpperCAmelCase ) writer.write_table(_UpperCAmelCase ) writer.close() return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> str: __snake_case : int = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) __snake_case : Optional[int] = {'data': DATA} with open(_UpperCAmelCase ,'w' ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ) -> Optional[Any]: __snake_case : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) __snake_case : str = {'data': DATA_DICT_OF_LISTS} with open(_UpperCAmelCase ,'w' ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ) -> Dict: __snake_case : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(_UpperCAmelCase ,'w' ) as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ) -> Tuple: __snake_case : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(_UpperCAmelCase ,'w' ) as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ) -> Optional[int]: __snake_case : int = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(_UpperCAmelCase ,'w' ) as f: for item in DATA_312: f.write(json.dumps(_UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ) -> List[str]: __snake_case : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(_UpperCAmelCase ,'w' ) as f: for item in DATA_STR: f.write(json.dumps(_UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Tuple ) -> str: import gzip __snake_case : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(_UpperCAmelCase ,'rb' ) as orig_file: with gzip.open(_UpperCAmelCase ,'wb' ) as zipped_file: zipped_file.writelines(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[Any] ) -> Optional[int]: import gzip __snake_case : str = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(_UpperCAmelCase ,'rb' ) as orig_file: with gzip.open(_UpperCAmelCase ,'wb' ) as zipped_file: zipped_file.writelines(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ,_UpperCAmelCase : int ) -> Union[str, Any]: __snake_case : Any = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> Tuple: __snake_case : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.join('nested' ,os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Any ) -> int: __snake_case : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(_UpperCAmelCase ,'w' ) as f: f.add(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) f.add(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ) -> Dict: __snake_case : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(_UpperCAmelCase ,'w' ) as f: f.add(_UpperCAmelCase ,arcname=os.path.join('nested' ,os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> int: __snake_case : int = ['0', '1', '2', '3'] __snake_case : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(_UpperCAmelCase ,'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[str] ) -> Dict: __snake_case : Optional[int] = ['0', '1', '2', '3'] __snake_case : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(_UpperCAmelCase ,'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[int]: __snake_case : Dict = ['0', '1', '2', '3'] __snake_case : str = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(_UpperCAmelCase ,'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ) -> Tuple: __snake_case : Optional[int] = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Any ) -> Optional[int]: __snake_case : str = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase ,arcname=os.path.join('main_dir' ,os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ) -> List[str]: __snake_case : str = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename('unsupported.ext' ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Optional[int] ) -> int: __snake_case : List[Any] = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) __snake_case : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(_UpperCAmelCase ,'w' ,encoding='utf-8' ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def a_ ( ) -> List[str]: return os.path.join('tests' ,'features' ,'data' ,'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def a_ ( ) -> int: return os.path.join('tests' ,'features' ,'data' ,'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ) -> Dict: __snake_case : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(_UpperCAmelCase ,'w' ) as f: f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase ,arcname=os.path.basename(_UpperCAmelCase ).replace('.jpg' ,'2.jpg' ) ) return path @pytest.fixture(scope='session' ) def a_ ( _UpperCAmelCase : int ) -> Optional[Any]: __snake_case : Tuple = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' ,'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' ,'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' ,'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' ,'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' ,'w' ) as f: f.write('bar\n' * 10 ) return data_dir
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : str ) -> str: return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' from math import sqrt def a_ ( _UpperCAmelCase : int ) -> bool: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" __snake_case : Tuple = True # 0 and 1 are none primes. if number <= 1: __snake_case : Dict = False for divisor in range(2 ,int(round(sqrt(_UpperCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __snake_case : str = False break # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'status' must been from type bool" return status def a_ ( _UpperCAmelCase : Optional[int] ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __snake_case : Union[str, Any] = list(range(2 ,n + 1 ) ) __snake_case : Tuple = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_UpperCAmelCase ) ): for j in range(i + 1 ,len(_UpperCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __snake_case : Dict = 0 # filters actual prime numbers. __snake_case : Optional[Any] = [x for x in begin_list if x != 0] # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n > 2), "'N' must been an int and > 2" __snake_case : Union[str, Any] = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 ,n + 1 ): if is_prime(_UpperCAmelCase ): ans.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Any ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and number >= 0, "'number' must been an int and >= 0" __snake_case : Any = [] # this list will be returns of the function. # potential prime number factors. __snake_case : Any = 2 __snake_case : Union[str, Any] = number if number == 0 or number == 1: ans.append(_UpperCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_UpperCAmelCase ): while quotient != 1: if is_prime(_UpperCAmelCase ) and (quotient % factor == 0): ans.append(_UpperCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" __snake_case : Optional[Any] = 0 # prime factorization of 'number' __snake_case : Dict = prime_factorization(_UpperCAmelCase ) __snake_case : Union[str, Any] = max(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type int" return ans def a_ ( _UpperCAmelCase : List[Any] ) -> str: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" __snake_case : List[str] = 0 # prime factorization of 'number' __snake_case : int = prime_factorization(_UpperCAmelCase ) __snake_case : int = min(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type int" return ans def a_ ( _UpperCAmelCase : List[str] ) -> Any: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 ,_UpperCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def a_ ( _UpperCAmelCase : str ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 ,_UpperCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def a_ ( _UpperCAmelCase : Tuple ) -> Tuple: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (number > 2) and is_even(_UpperCAmelCase ) ), "'number' must been an int, even and > 2" __snake_case : Optional[Any] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __snake_case : List[str] = get_prime_numbers(_UpperCAmelCase ) __snake_case : Optional[Any] = len(_UpperCAmelCase ) # run variable for while-loops. __snake_case : Any = 0 __snake_case : Tuple = None # exit variable. for break up the loops __snake_case : Optional[int] = True while i < len_pn and loop: __snake_case : Union[str, Any] = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __snake_case : Optional[int] = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (len(_UpperCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __snake_case : Optional[Any] = 0 while numbera != 0: __snake_case : Tuple = numbera % numbera __snake_case : Any = numbera __snake_case : Tuple = rest # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ) -> Any: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __snake_case : Any = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __snake_case : Optional[int] = prime_factorization(_UpperCAmelCase ) __snake_case : Dict = prime_factorization(_UpperCAmelCase ) elif numbera == 1 or numbera == 1: __snake_case : Union[str, Any] = [] __snake_case : Union[str, Any] = [] __snake_case : List[str] = max(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : Union[str, Any] = 0 __snake_case : str = 0 __snake_case : Optional[int] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __snake_case : Optional[Any] = prime_fac_a.count(_UpperCAmelCase ) __snake_case : Optional[int] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(max(_UpperCAmelCase ,_UpperCAmelCase ) ): ans *= n else: __snake_case : List[str] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ): ans *= n done.append(_UpperCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __snake_case : List[Any] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ): ans *= n done.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def a_ ( _UpperCAmelCase : Tuple ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'number' must been a positive int" __snake_case : int = 0 __snake_case : Tuple = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_UpperCAmelCase ): ans += 1 # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and is_prime( _UpperCAmelCase ), "'ans' must been a prime number and from type int" return ans def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: assert ( is_prime(_UpperCAmelCase ) and is_prime(_UpperCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __snake_case : Any = p_number_a + 1 # jump to the next number __snake_case : List[Any] = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_UpperCAmelCase ): number += 1 while number < p_number_a: ans.append(_UpperCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_UpperCAmelCase ): number += 1 # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ans[0] != p_number_a and ans[len(_UpperCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def a_ ( _UpperCAmelCase : Any ) -> str: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 1), "'n' must been int and >= 1" __snake_case : Union[str, Any] = [] # will be returned. for divisor in range(1 ,n + 1 ): if n % divisor == 0: ans.append(_UpperCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_UpperCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def a_ ( _UpperCAmelCase : List[Any] ) -> List[str]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" __snake_case : Tuple = get_divisors(_UpperCAmelCase ) # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (divisors[0] == 1) and (divisors[len(_UpperCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ) -> Tuple: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __snake_case : Optional[int] = gcd(abs(_UpperCAmelCase ) ,abs(_UpperCAmelCase ) ) # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def a_ ( _UpperCAmelCase : int ) -> int: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" __snake_case : List[str] = 1 # this will be return. for factor in range(1 ,n + 1 ): ans *= factor return ans def a_ ( _UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" __snake_case : int = 0 __snake_case : List[str] = 1 __snake_case : Optional[Any] = 1 # this will be return for _ in range(n - 1 ): __snake_case : Dict = ans ans += fiba __snake_case : Dict = tmp return ans
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __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 ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
1
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
1
'''simple docstring''' from __future__ import annotations def a_ ( _UpperCAmelCase : list ,_UpperCAmelCase : int | None = None ,_UpperCAmelCase : int | None = None ) -> None: if start is None: __snake_case : Dict = 0 if end is None: __snake_case : Optional[Any] = len(_UpperCAmelCase ) - 1 if start >= end: return __snake_case : List[str] = (start + end) // 2 slowsort(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) slowsort(_UpperCAmelCase ,mid + 1 ,_UpperCAmelCase ) if sequence[end] < sequence[mid]: __snake_case , __snake_case : Union[str, Any] = sequence[mid], sequence[end] slowsort(_UpperCAmelCase ,_UpperCAmelCase ,end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
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__ : Dict = logging.get_logger(__name__) A__ : Dict = { '''openai/whisper-base''': '''https://huggingface.co/openai/whisper-base/resolve/main/config.json''', } # fmt: off A__ : List[Any] = [ 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__ : str = [ 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 snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''whisper''' A__ = ['''past_key_values'''] A__ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Union[str, Any] , __a : Dict=51865 , __a : int=80 , __a : int=6 , __a : Tuple=4 , __a : Any=6 , __a : str=4 , __a : Dict=1536 , __a : List[Any]=1536 , __a : List[Any]=0.0 , __a : int=0.0 , __a : Any=50257 , __a : List[str]=True , __a : List[Any]=True , __a : List[str]="gelu" , __a : Union[str, Any]=256 , __a : List[str]=0.0 , __a : str=0.0 , __a : List[Any]=0.0 , __a : int=0.0_2 , __a : List[Any]=False , __a : List[str]=1500 , __a : Dict=448 , __a : Tuple=50256 , __a : List[str]=50256 , __a : Any=50256 , __a : Optional[int]=None , __a : Any=[220, 50256] , __a : Dict=False , __a : Dict=256 , __a : Dict=False , __a : Dict=0.0_5 , __a : Optional[int]=10 , __a : str=2 , __a : int=0.0 , __a : int=10 , __a : int=0 , __a : int=7 , **__a : Optional[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : Dict = vocab_size __snake_case : List[str] = num_mel_bins __snake_case : str = d_model __snake_case : Dict = encoder_layers __snake_case : Tuple = encoder_attention_heads __snake_case : Dict = decoder_layers __snake_case : int = decoder_attention_heads __snake_case : List[Any] = decoder_ffn_dim __snake_case : List[Any] = encoder_ffn_dim __snake_case : Optional[Any] = dropout __snake_case : Tuple = attention_dropout __snake_case : str = activation_dropout __snake_case : Tuple = activation_function __snake_case : List[Any] = init_std __snake_case : Dict = encoder_layerdrop __snake_case : Tuple = decoder_layerdrop __snake_case : Dict = use_cache __snake_case : List[Any] = encoder_layers __snake_case : Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True __snake_case : Any = max_source_positions __snake_case : int = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. __snake_case : Any = classifier_proj_size __snake_case : str = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __snake_case : Optional[Any] = apply_spec_augment __snake_case : List[str] = mask_time_prob __snake_case : List[str] = mask_time_length __snake_case : Union[str, Any] = mask_time_min_masks __snake_case : Optional[int] = mask_feature_prob __snake_case : Union[str, Any] = mask_feature_length __snake_case : Union[str, Any] = mask_feature_min_masks __snake_case : Dict = median_filter_width super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , decoder_start_token_id=__a , suppress_tokens=__a , begin_suppress_tokens=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Any = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ] ) if self.use_past: __snake_case : List[str] = {0: 'batch'} else: __snake_case : Dict = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs def A_ ( self : Optional[int] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional["TensorType"] = None , __a : int = 22050 , __a : float = 5.0 , __a : int = 220 , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = OrderedDict() __snake_case : Any = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=__a , framework=__a , sampling_rate=__a , time_duration=__a , frequency=__a , ) __snake_case : Union[str, Any] = encoder_inputs['input_features'].shape[2] __snake_case : Optional[Any] = encoder_sequence_length // 2 if self.use_past else seq_length __snake_case : List[Any] = super().generate_dummy_inputs( preprocessor.tokenizer , __a , __a , __a , __a ) __snake_case : Any = encoder_inputs.pop('input_features' ) __snake_case : Dict = decoder_inputs.pop('decoder_input_ids' ) if "past_key_values" in decoder_inputs: __snake_case : Union[str, Any] = decoder_inputs.pop('past_key_values' ) return dummy_inputs @property def A_ ( self : Union[str, Any] ) -> float: '''simple docstring''' return 1e-3
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset A__ : Optional[int] = pd.read_csv( '''https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/''' '''position_salaries.csv''' ) A__ : Optional[int] = dataset.iloc[:, 1:2].values A__ : Any = dataset.iloc[:, 2].values A__ , A__ , A__ , A__ : Dict = train_test_split(X, y, test_size=0.2, random_state=0) A__ : str = PolynomialFeatures(degree=4) A__ : Optional[Any] = poly_reg.fit_transform(X) A__ : Dict = LinearRegression() pol_reg.fit(X_poly, y) def a_ ( ) -> Dict: plt.scatter(_UpperCAmelCase ,_UpperCAmelCase ,color='red' ) plt.plot(_UpperCAmelCase ,pol_reg.predict(poly_reg.fit_transform(_UpperCAmelCase ) ) ,color='blue' ) plt.title('Truth or Bluff (Linear Regression)' ) plt.xlabel('Position level' ) plt.ylabel('Salary' ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Union[str, Any] , *__a : List[str] , **__a : Optional[int] ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Tuple , *__a : List[str] , **__a : Optional[Any] ) -> Dict: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Any , *__a : List[str] , **__a : List[str] ) -> Any: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : int , *__a : int , **__a : int ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Any , *__a : Dict , **__a : List[str] ) -> Tuple: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : int , *__a : int , **__a : List[Any] ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *__a : str , **__a : int ) -> str: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Optional[int] , *__a : Union[str, Any] , **__a : Union[str, Any] ) -> Tuple: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Optional[int] , *__a : List[Any] , **__a : Union[str, Any] ) -> int: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *__a : Dict , **__a : Dict ) -> int: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : List[Any] , *__a : int , **__a : Optional[Any] ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : int , *__a : List[Any] , **__a : List[Any] ) -> List[str]: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[int] , *__a : str , **__a : List[str] ) -> Tuple: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Tuple , *__a : Optional[int] , **__a : List[str] ) -> Any: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Dict , *__a : Optional[Any] , **__a : Tuple ) -> Tuple: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class snake_case__ ( metaclass=SCREAMING_SNAKE_CASE_ ): A__ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *__a : Union[str, Any] , **__a : List[str] ) -> List[str]: '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : List[Any] , *__a : Dict , **__a : str ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def A_ ( cls : Tuple , *__a : int , **__a : Any ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] )
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
'''simple docstring''' from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
0
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
1
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging A__ : Optional[int] = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : Union[tf.Tensor, np.ndarray] ) -> List[int]: if isinstance(_UpperCAmelCase ,np.ndarray ): return list(tensor.shape ) __snake_case : Optional[Any] = tf.shape(_UpperCAmelCase ) if tensor.shape == tf.TensorShape(_UpperCAmelCase ): return dynamic __snake_case : int = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(_UpperCAmelCase )] def a_ ( _UpperCAmelCase : tf.Tensor ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[str] = None ) -> tf.Tensor: return tf.nn.softmax(logits=logits + 1E-9 ,axis=_UpperCAmelCase ,name=_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : str=1E-5 ,_UpperCAmelCase : Union[str, Any]=-1 ) -> str: # This is a very simplified functional layernorm, designed to duplicate # the functionality of PyTorch nn.functional.layer_norm when this is needed to port # models in Transformers. if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' ) # Get mean and variance on the axis to be normalized __snake_case , __snake_case : Union[str, Any] = tf.nn.moments(_UpperCAmelCase ,axes=[axis] ,keepdims=_UpperCAmelCase ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis __snake_case : Optional[Any] = [1] * inputs.shape.rank __snake_case : str = shape_list(_UpperCAmelCase )[axis] __snake_case : Any = tf.reshape(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : int = tf.reshape(_UpperCAmelCase ,_UpperCAmelCase ) # Compute layer normalization using the batch_normalization # function. __snake_case : int = tf.nn.batch_normalization( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,offset=_UpperCAmelCase ,scale=_UpperCAmelCase ,variance_epsilon=_UpperCAmelCase ,) return outputs def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Dict=0 ,_UpperCAmelCase : int=-1 ) -> Dict: # Replicates the behavior of torch.flatten in TF # If end_dim or start_dim is negative, count them from the end if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input __snake_case : Any = tf.shape(_UpperCAmelCase ) __snake_case : int = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) __snake_case : Dict = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] ,axis=0 ) return tf.reshape(_UpperCAmelCase ,_UpperCAmelCase ) def a_ ( _UpperCAmelCase : tf.Tensor ) -> tf.Tensor: if not isinstance(_UpperCAmelCase ,tf.Tensor ): __snake_case : List[str] = tf.convert_to_tensor(_UpperCAmelCase ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: __snake_case : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: __snake_case : List[str] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) __snake_case : Any = ( tf.cast(1 ,encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def a_ ( _UpperCAmelCase : tf.Tensor ,_UpperCAmelCase : int ,_UpperCAmelCase : str = "input_ids" ) -> None: tf.debugging.assert_less( _UpperCAmelCase ,tf.cast(_UpperCAmelCase ,dtype=tensor.dtype ) ,message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(_UpperCAmelCase )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) ,) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple ) -> List[str]: __snake_case : Union[str, Any] = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. __snake_case : Any = [x for x in data if len(_UpperCAmelCase ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) __snake_case : Tuple = np.asarray(_UpperCAmelCase ) __snake_case : List[Any] = 1 __snake_case : List[str] = np.array_split(_UpperCAmelCase ,_UpperCAmelCase ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 __snake_case : List[str] = np.array_split(_UpperCAmelCase ,_UpperCAmelCase ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(_UpperCAmelCase ): __snake_case : Dict = chunk_data else: __snake_case : Optional[int] = data def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: if name in group.attrs: __snake_case : List[str] = [n.decode('utf8' ) if hasattr(_UpperCAmelCase ,'decode' ) else n for n in group.attrs[name]] else: __snake_case : int = [] __snake_case : Tuple = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8' ) if hasattr(_UpperCAmelCase ,'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] ) chunk_id += 1 return data def a_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: def _expand_single_ad_tensor(_UpperCAmelCase : Tuple ): if isinstance(_UpperCAmelCase ,tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(_UpperCAmelCase ,axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor ,_UpperCAmelCase )
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __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 A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A__ : Optional[Any] = logging.get_logger(__name__) A__ : str = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : Union[str, Any] = { '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } A__ : Any = { '''gpt-neox-20b''': 2_0_4_8, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , __a : List[str]=None , __a : List[str]=None , __a : str=None , __a : Optional[int]="<|endoftext|>" , __a : Any="<|endoftext|>" , __a : Tuple="<|endoftext|>" , __a : str=False , **__a : Union[str, Any] , ) -> Optional[int]: '''simple docstring''' super().__init__( __a , __a , tokenizer_file=__a , unk_token=__a , bos_token=__a , eos_token=__a , add_prefix_space=__a , **__a , ) __snake_case : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __a ) != add_prefix_space: __snake_case : Any = getattr(__a , pre_tok_state.pop('type' ) ) __snake_case : int = add_prefix_space __snake_case : Optional[Any] = pre_tok_class(**__a ) __snake_case : Union[str, Any] = add_prefix_space def A_ ( self : List[str] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Dict = self._tokenizer.model.save(__a , name=__a ) return tuple(__a ) def A_ ( self : str , __a : "Conversation" ) -> List[int]: '''simple docstring''' __snake_case : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] ) if len(__a ) > self.model_max_length: __snake_case : Tuple = input_ids[-self.model_max_length :] return input_ids
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case__ ( unittest.TestCase ): def A_ ( self : Optional[Any] ) -> Any: '''simple docstring''' # A mock response for an HTTP head request to emulate server down __snake_case : List[Any] = mock.Mock() __snake_case : Any = 500 __snake_case : Optional[int] = {} __snake_case : Optional[int] = HTTPError __snake_case : List[str] = {} # Download this model to make sure it's in the cache. __snake_case : Union[str, Any] = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=__a ) as mock_head: __snake_case : Tuple = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' # A mock response for an HTTP head request to emulate server down __snake_case : Union[str, Any] = mock.Mock() __snake_case : Tuple = 500 __snake_case : int = {} __snake_case : List[str] = HTTPError __snake_case : List[Any] = {} # Download this model to make sure it's in the cache. __snake_case : str = GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=__a ) as mock_head: __snake_case : Dict = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def A_ ( self : List[Any] ) -> str: '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 try: __snake_case : Optional[int] = tempfile.mktemp() with open(__a , 'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , __a ) __snake_case : Any = AlbertTokenizer.from_pretrained(__a ) finally: os.remove(__a ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' , 'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' , __a ) __snake_case : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def A_ ( self : List[str] ) -> Any: '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 __snake_case : int = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class snake_case__ ( unittest.TestCase ): A__ = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def A_ ( cls : int ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TOKEN HfFolder.save_token(__a ) @classmethod def A_ ( cls : List[Any] ) -> Dict: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Optional[Any] = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : int = BertTokenizer(__a ) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__a , repo_id='test-tokenizer' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : Union[str, Any] = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : str = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Union[str, Any] = BertTokenizer(__a ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token ) __snake_case : List[str] = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( __a , repo_id='valid_org/test-tokenizer-org' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : Dict = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def A_ ( self : Optional[Any] ) -> Any: '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Union[str, Any] = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Optional[Any] = CustomTokenizer(__a ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Dict = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Dict = BertTokenizerFast.from_pretrained(__a ) bert_tokenizer.save_pretrained(__a ) __snake_case : Optional[int] = CustomTokenizerFast.from_pretrained(__a ) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizerFast' ) __snake_case : int = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=__a , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS]', ' This is a ', 'extra_id_100'] ) def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) , ['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) , ['BC', 'A'] ) def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Dict = Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def A_ ( self : str ) -> List[Any]: '''simple docstring''' __snake_case : Dict = Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def A_ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) , ['AB', 'C'] ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) , ['ABC', 'D'] ) def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' # Even if the offsets are wrong, we necessarily output correct string # parts. __snake_case : Optional[Any] = Trie() __snake_case : Dict = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(__a , ['AB', 'C'] )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''Salesforce/blip-image-captioning-base''' A__ = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) A__ = '''image_captioner''' A__ = AutoModelForVisionaSeq A__ = ['''image'''] A__ = ['''text'''] def __init__( self : Optional[Any] , *__a : List[Any] , **__a : List[str] ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*__a , **__a ) def A_ ( self : Optional[Any] , __a : "Image" ) -> int: '''simple docstring''' return self.pre_processor(images=__a , return_tensors='pt' ) def A_ ( self : Union[str, Any] , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' return self.model.generate(**__a ) def A_ ( self : Any , __a : List[str] ) -> Any: '''simple docstring''' return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a_ ( _UpperCAmelCase : List[str] ) -> Any: if "cls_token" in name: __snake_case : int = name.replace('cls_token' ,'vit.embeddings.cls_token' ) if "mask_token" in name: __snake_case : Tuple = name.replace('mask_token' ,'decoder.mask_token' ) if "decoder_pos_embed" in name: __snake_case : List[Any] = name.replace('decoder_pos_embed' ,'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: __snake_case : Tuple = name.replace('pos_embed' ,'vit.embeddings.position_embeddings' ) if "patch_embed.proj" in name: __snake_case : Tuple = name.replace('patch_embed.proj' ,'vit.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: __snake_case : List[str] = name.replace('patch_embed.norm' ,'vit.embeddings.norm' ) if "decoder_blocks" in name: __snake_case : Union[str, Any] = name.replace('decoder_blocks' ,'decoder.decoder_layers' ) if "blocks" in name: __snake_case : Any = name.replace('blocks' ,'vit.encoder.layer' ) if "attn.proj" in name: __snake_case : Optional[int] = name.replace('attn.proj' ,'attention.output.dense' ) if "attn" in name: __snake_case : str = name.replace('attn' ,'attention.self' ) if "norm1" in name: __snake_case : int = name.replace('norm1' ,'layernorm_before' ) if "norm2" in name: __snake_case : List[Any] = name.replace('norm2' ,'layernorm_after' ) if "mlp.fc1" in name: __snake_case : Union[str, Any] = name.replace('mlp.fc1' ,'intermediate.dense' ) if "mlp.fc2" in name: __snake_case : List[str] = name.replace('mlp.fc2' ,'output.dense' ) if "decoder_embed" in name: __snake_case : Optional[Any] = name.replace('decoder_embed' ,'decoder.decoder_embed' ) if "decoder_norm" in name: __snake_case : str = name.replace('decoder_norm' ,'decoder.decoder_norm' ) if "decoder_pred" in name: __snake_case : List[Any] = name.replace('decoder_pred' ,'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name: __snake_case : Optional[Any] = name.replace('norm.weight' ,'vit.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name: __snake_case : Tuple = name.replace('norm.bias' ,'vit.layernorm.bias' ) return name def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> Optional[int]: for key in orig_state_dict.copy().keys(): __snake_case : int = orig_state_dict.pop(_UpperCAmelCase ) if "qkv" in key: __snake_case : List[str] = key.split('.' ) __snake_case : Union[str, Any] = int(key_split[1] ) if "decoder_blocks" in key: __snake_case : Union[str, Any] = config.decoder_hidden_size __snake_case : List[Any] = 'decoder.decoder_layers.' if "weight" in key: __snake_case : Optional[Any] = val[:dim, :] __snake_case : Dict = val[dim : dim * 2, :] __snake_case : str = val[-dim:, :] elif "bias" in key: __snake_case : List[Any] = val[:dim] __snake_case : Optional[int] = val[dim : dim * 2] __snake_case : List[Any] = val[-dim:] else: __snake_case : str = config.hidden_size __snake_case : Tuple = 'vit.encoder.layer.' if "weight" in key: __snake_case : int = val[:dim, :] __snake_case : Optional[int] = val[dim : dim * 2, :] __snake_case : List[Any] = val[-dim:, :] elif "bias" in key: __snake_case : Union[str, Any] = val[:dim] __snake_case : int = val[dim : dim * 2] __snake_case : Union[str, Any] = val[-dim:] else: __snake_case : str = val return orig_state_dict def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Dict ) -> Optional[Any]: __snake_case : Tuple = ViTMAEConfig() if "large" in checkpoint_url: __snake_case : Optional[int] = 10_24 __snake_case : List[Any] = 40_96 __snake_case : Tuple = 24 __snake_case : Union[str, Any] = 16 elif "huge" in checkpoint_url: __snake_case : Optional[int] = 14 __snake_case : Tuple = 12_80 __snake_case : Tuple = 51_20 __snake_case : Tuple = 32 __snake_case : Optional[int] = 16 __snake_case : Tuple = ViTMAEForPreTraining(_UpperCAmelCase ) __snake_case : str = torch.hub.load_state_dict_from_url(_UpperCAmelCase ,map_location='cpu' )['model'] __snake_case : Union[str, Any] = ViTMAEImageProcessor(size=config.image_size ) __snake_case : str = convert_state_dict(_UpperCAmelCase ,_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() __snake_case : Any = 'https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg' __snake_case : Union[str, Any] = Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ) __snake_case : int = ViTMAEImageProcessor(size=config.image_size ) __snake_case : Optional[int] = image_processor(images=_UpperCAmelCase ,return_tensors='pt' ) # forward pass torch.manual_seed(2 ) __snake_case : Optional[Any] = model(**_UpperCAmelCase ) __snake_case : Any = outputs.logits if "large" in checkpoint_url: __snake_case : Tuple = torch.tensor( [[-0.7_3_0_9, -0.7_1_2_8, -1.0_1_6_9], [-1.0_1_6_1, -0.9_0_5_8, -1.1_8_7_8], [-1.0_4_7_8, -0.9_4_1_1, -1.1_9_1_1]] ) elif "huge" in checkpoint_url: __snake_case : List[Any] = torch.tensor( [[-1.1_5_9_9, -0.9_1_9_9, -1.2_2_2_1], [-1.1_9_5_2, -0.9_2_6_9, -1.2_3_0_7], [-1.2_1_4_3, -0.9_3_3_7, -1.2_2_6_2]] ) else: __snake_case : Optional[Any] = torch.tensor( [[-0.9_1_9_2, -0.8_4_8_1, -1.1_2_5_9], [-1.1_3_4_9, -1.0_0_3_4, -1.2_5_9_9], [-1.1_7_5_7, -1.0_4_2_9, -1.2_7_2_6]] ) # verify logits assert torch.allclose(logits[0, :3, :3] ,_UpperCAmelCase ,atol=1E-4 ) print(f'''Saving model 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__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
'''simple docstring''' from math import ceil, sqrt def a_ ( _UpperCAmelCase : int = 1_00_00_00 ) -> int: __snake_case : Union[str, Any] = 0 for outer_width in range(3 ,(limit // 4) + 2 ): if outer_width**2 > limit: __snake_case : Tuple = max(ceil(sqrt(outer_width**2 - limit ) ) ,1 ) else: __snake_case : Any = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F"""{solution() = }""")
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 10_00 ) -> int: __snake_case , __snake_case : Union[str, Any] = 1, 1 __snake_case : Dict = [] for i in range(1 ,n + 1 ): __snake_case : Optional[Any] = prev_numerator + 2 * prev_denominator __snake_case : int = prev_numerator + prev_denominator if len(str(_UpperCAmelCase ) ) > len(str(_UpperCAmelCase ) ): result.append(_UpperCAmelCase ) __snake_case : int = numerator __snake_case : Union[str, Any] = denominator return len(_UpperCAmelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__ : List[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] = ['''MobileViTFeatureExtractor'''] A__ : Optional[int] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys A__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html A__ : Dict = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class snake_case__ : A__ = PegasusConfig A__ = {} A__ = '''gelu''' def __init__( self : Any , __a : Dict , __a : Tuple=13 , __a : Optional[int]=7 , __a : str=True , __a : str=False , __a : Any=99 , __a : Tuple=32 , __a : str=5 , __a : int=4 , __a : Optional[int]=37 , __a : Tuple=0.1 , __a : str=0.1 , __a : Optional[int]=20 , __a : Optional[int]=2 , __a : Union[str, Any]=1 , __a : Optional[int]=0 , ) -> List[str]: '''simple docstring''' __snake_case : Tuple = parent __snake_case : List[str] = batch_size __snake_case : Union[str, Any] = seq_length __snake_case : List[str] = is_training __snake_case : List[Any] = use_labels __snake_case : int = vocab_size __snake_case : List[str] = hidden_size __snake_case : List[Any] = num_hidden_layers __snake_case : str = num_attention_heads __snake_case : Dict = intermediate_size __snake_case : str = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : List[Any] = max_position_embeddings __snake_case : List[str] = eos_token_id __snake_case : Any = pad_token_id __snake_case : str = bos_token_id def A_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __snake_case : List[str] = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __snake_case : Any = np.concatenate([input_ids, eos_tensor] , axis=1 ) __snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __snake_case : Optional[Any] = prepare_pegasus_inputs_dict(__a , __a , __a ) return config, inputs_dict def A_ ( self : Union[str, Any] , __a : Dict , __a : int , __a : int ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = 20 __snake_case : int = model_class_name(__a ) __snake_case : List[Any] = model.encode(inputs_dict['input_ids'] ) __snake_case , __snake_case : List[Any] = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) __snake_case : List[str] = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) __snake_case : List[Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='i4' ) __snake_case : int = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __snake_case : Dict = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) __snake_case : Dict = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) __snake_case : Optional[int] = model.decode( decoder_input_ids[:, -1:] , __a , decoder_attention_mask=__a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__a , ) __snake_case : List[str] = model.decode(__a , __a ) __snake_case : Any = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def A_ ( self : Any , __a : Any , __a : List[str] , __a : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Dict = 20 __snake_case : List[str] = model_class_name(__a ) __snake_case : Optional[Any] = model.encode(inputs_dict['input_ids'] ) __snake_case , __snake_case : Optional[int] = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) __snake_case : Union[str, Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __snake_case : Dict = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) __snake_case : Optional[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __snake_case : List[Any] = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) __snake_case : Optional[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) __snake_case : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , __a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__a , decoder_position_ids=__a , ) __snake_case : Optional[Any] = model.decode(__a , __a , decoder_attention_mask=__a ) __snake_case : Any = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Optional[int]=None ,) -> Optional[int]: if attention_mask is None: __snake_case : Union[str, Any] = np.not_equal(_UpperCAmelCase ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __snake_case : List[str] = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) A__ = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () A__ = True A__ = False A__ = False A__ = False def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : str = FlaxPegasusModelTester(self ) __snake_case : List[str] = ConfigTester(self , config_class=__a ) def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case , __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__a , __a , __a ) def A_ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' __snake_case , __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__a , __a , __a ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __snake_case : Dict = self._prepare_for_class(__a , __a ) __snake_case : List[str] = model_class(__a ) @jax.jit def encode_jitted(__a : Union[str, Any] , __a : Optional[Any]=None , **__a : Any ): return model.encode(input_ids=__a , attention_mask=__a ) with self.subTest('JIT Enabled' ): __snake_case : int = encode_jitted(**__a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __snake_case : Dict = encode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __snake_case : Optional[int] = model_class(__a ) __snake_case : Tuple = model.encode(inputs_dict['input_ids'] , inputs_dict['attention_mask'] ) __snake_case : Optional[int] = { 'decoder_input_ids': inputs_dict['decoder_input_ids'], 'decoder_attention_mask': inputs_dict['decoder_attention_mask'], 'encoder_outputs': encoder_outputs, } @jax.jit def decode_jitted(__a : List[str] , __a : Dict , __a : int ): return model.decode( decoder_input_ids=__a , decoder_attention_mask=__a , encoder_outputs=__a , ) with self.subTest('JIT Enabled' ): __snake_case : Tuple = decode_jitted(**__a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __snake_case : str = decode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def A_ ( self : Dict ) -> str: '''simple docstring''' for model_class_name in self.all_model_classes: __snake_case : int = model_class_name.from_pretrained('google/pegasus-large' , from_pt=__a ) __snake_case : List[Any] = np.ones((1, 1) ) __snake_case : Dict = model(__a ) self.assertIsNotNone(__a ) @slow def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = FlaxPegasusForConditionalGeneration.from_pretrained('google/pegasus-xsum' ) __snake_case : List[str] = PegasusTokenizer.from_pretrained('google/pegasus-xsum' ) __snake_case : str = [ ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.', ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ', ] __snake_case : Optional[int] = [ 'California\'s largest electricity provider has turned off power to hundreds of thousands of customers.', 'Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.', ] __snake_case : Dict = tokenizer(__a , return_tensors='np' , truncation=__a , max_length=512 , padding=__a ) __snake_case : Any = model.generate(**__a , num_beams=2 ).sequences __snake_case : List[Any] = tokenizer.batch_decode(__a , skip_special_tokens=__a ) assert tgt_text == decoded
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' from __future__ import annotations from scipy.special import comb # type: ignore class snake_case__ : def __init__( self : int , __a : list[tuple[float, float]] ) -> Dict: '''simple docstring''' __snake_case : List[Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __snake_case : Union[str, Any] = len(__a ) - 1 def A_ ( self : str , __a : float ) -> list[float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." __snake_case : list[float] = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , __a ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(__a ) , 5 ) == 1 return output_values def A_ ( self : List[Any] , __a : float ) -> tuple[float, float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." __snake_case : List[Any] = self.basis_function(__a ) __snake_case : List[Any] = 0.0 __snake_case : List[Any] = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def A_ ( self : Any , __a : float = 0.0_1 ) -> str: '''simple docstring''' from matplotlib import pyplot as plt # type: ignore __snake_case : list[float] = [] # x coordinates of points to plot __snake_case : list[float] = [] # y coordinates of points to plot __snake_case : Dict = 0.0 while t <= 1: __snake_case : Optional[Any] = self.bezier_curve_function(__a ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size __snake_case : List[Any] = [i[0] for i in self.list_of_points] __snake_case : Optional[int] = [i[1] for i in self.list_of_points] plt.plot( __a , __a , color='blue' , label='Curve of Degree ' + str(self.degree ) , ) plt.scatter(__a , __a , color='red' , label='Control Points' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : List[Any] = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json''', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''glpn''' def __init__( self : Tuple , __a : int=3 , __a : Union[str, Any]=4 , __a : List[Any]=[2, 2, 2, 2] , __a : Dict=[8, 4, 2, 1] , __a : str=[32, 64, 160, 256] , __a : Optional[Any]=[7, 3, 3, 3] , __a : Optional[int]=[4, 2, 2, 2] , __a : int=[1, 2, 5, 8] , __a : Any=[4, 4, 4, 4] , __a : Dict="gelu" , __a : List[Any]=0.0 , __a : Any=0.0 , __a : Optional[Any]=0.0_2 , __a : Optional[Any]=0.1 , __a : Union[str, Any]=1e-6 , __a : str=64 , __a : List[str]=10 , __a : Dict=-1 , **__a : Union[str, Any] , ) -> List[Any]: '''simple docstring''' super().__init__(**__a ) __snake_case : List[Any] = num_channels __snake_case : Tuple = num_encoder_blocks __snake_case : Optional[Any] = depths __snake_case : Any = sr_ratios __snake_case : int = hidden_sizes __snake_case : Any = patch_sizes __snake_case : Optional[int] = strides __snake_case : Dict = mlp_ratios __snake_case : int = num_attention_heads __snake_case : List[Any] = hidden_act __snake_case : Optional[int] = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Optional[int] = initializer_range __snake_case : Union[str, Any] = drop_path_rate __snake_case : Any = layer_norm_eps __snake_case : Any = decoder_hidden_size __snake_case : str = max_depth __snake_case : List[Any] = head_in_index
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any]=[] ) -> str: __snake_case : Any = size[0] - overlap_pixels * 2 __snake_case : List[str] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels __snake_case : Any = np.ones((size_y, size_x) ,dtype=np.uinta ) * 2_55 __snake_case : Optional[Any] = np.pad(_UpperCAmelCase ,mode='linear_ramp' ,pad_width=_UpperCAmelCase ,end_values=0 ) if "l" in remove_borders: __snake_case : Dict = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: __snake_case : Tuple = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: __snake_case : Any = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: __snake_case : Tuple = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Dict ) -> Union[str, Any]: return max(_UpperCAmelCase ,min(_UpperCAmelCase ,_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : [int] ,_UpperCAmelCase : [int] ,_UpperCAmelCase : [int] ) -> Optional[Any]: return ( clamp(rect[0] ,min[0] ,max[0] ), clamp(rect[1] ,min[1] ,max[1] ), clamp(rect[2] ,min[0] ,max[0] ), clamp(rect[3] ,min[1] ,max[1] ), ) def a_ ( _UpperCAmelCase : [int] ,_UpperCAmelCase : int ,_UpperCAmelCase : [int] ) -> Union[str, Any]: __snake_case : List[Any] = list(_UpperCAmelCase ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap __snake_case : Tuple = clamp_rect(_UpperCAmelCase ,[0, 0] ,[image_size[0], image_size[1]] ) return rect def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ) -> List[str]: __snake_case : Union[str, Any] = Image.new('RGB' ,(tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) ,Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) ,(0, 0) ,) result.paste(_UpperCAmelCase ,(original_slice, 0) ) return result def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> List[str]: __snake_case : Tuple = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) __snake_case : Dict = tile.crop(_UpperCAmelCase ) return tile def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ) -> Tuple: __snake_case : List[str] = n % d return n - divisor class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Any , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : DDPMScheduler , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : int = 350 , ) -> Any: '''simple docstring''' super().__init__( vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , low_res_scheduler=__a , scheduler=__a , max_noise_level=__a , ) def A_ ( self : int , __a : Optional[int] , __a : str , __a : Any , __a : Optional[int] , __a : Optional[int] , __a : Tuple , __a : List[str] , **__a : Optional[int] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) __snake_case : Tuple = add_overlap_rect(__a , __a , image.size ) __snake_case : Optional[Any] = image.crop(__a ) __snake_case : Optional[Any] = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] __snake_case : Optional[int] = translated_slice_x - (original_image_slice / 2) __snake_case : Tuple = max(0 , __a ) __snake_case : Optional[int] = squeeze_tile(__a , __a , __a , __a ) __snake_case : Optional[int] = to_input.size __snake_case : Optional[Any] = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) __snake_case : Union[str, Any] = super(__a , self ).__call__(image=__a , **__a ).images[0] __snake_case : List[Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) __snake_case : Optional[int] = unsqueeze_tile(__a , __a ) __snake_case : Optional[Any] = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) __snake_case : Dict = [] if x == 0: remove_borders.append('l' ) elif crop_rect[2] == image.size[0]: remove_borders.append('r' ) if y == 0: remove_borders.append('t' ) elif crop_rect[3] == image.size[1]: remove_borders.append('b' ) __snake_case : Optional[Any] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__a ) , mode='L' , ) final_image.paste( __a , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __a ) @torch.no_grad() def __call__( self : List[Any] , __a : Union[str, List[str]] , __a : Union[PIL.Image.Image, List[PIL.Image.Image]] , __a : int = 75 , __a : float = 9.0 , __a : int = 50 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , __a : int = 128 , __a : int = 32 , __a : int = 32 , ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) ) __snake_case : List[str] = math.ceil(image.size[0] / tile_size ) __snake_case : List[str] = math.ceil(image.size[1] / tile_size ) __snake_case : int = tcx * tcy __snake_case : int = 0 for y in range(__a ): for x in range(__a ): self._process_tile( __a , __a , __a , __a , __a , __a , __a , prompt=__a , num_inference_steps=__a , guidance_scale=__a , noise_level=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , ) current_count += 1 if callback is not None: callback({'progress': current_count / total_tile_count, 'image': final_image} ) return final_image def a_ ( ) -> int: # Run a demo __snake_case : Optional[Any] = 'stabilityai/stable-diffusion-x4-upscaler' __snake_case : str = StableDiffusionTiledUpscalePipeline.from_pretrained(_UpperCAmelCase ,revision='fp16' ,torch_dtype=torch.floataa ) __snake_case : Tuple = pipe.to('cuda' ) __snake_case : Any = Image.open('../../docs/source/imgs/diffusers_library.jpg' ) def callback(_UpperCAmelCase : Union[str, Any] ): print(f'''progress: {obj["progress"]:.4f}''' ) obj["image"].save('diffusers_library_progress.jpg' ) __snake_case : Tuple = pipe(image=_UpperCAmelCase ,prompt='Black font, white background, vector' ,noise_level=40 ,callback=_UpperCAmelCase ) final_image.save('diffusers_library.jpg' ) if __name__ == "__main__": main()
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __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 ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class snake_case__ ( unittest.TestCase ): A__ = ViTImageProcessor if is_vision_available() else None @property def A_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = (3, 32, 128) __snake_case : Tuple = tempfile.mkdtemp() # fmt: off __snake_case : Optional[int] = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # fmt: on __snake_case : Optional[int] = dict(zip(__a , range(len(__a ) ) ) ) __snake_case : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__a ) + '\n' ) __snake_case : Union[str, Any] = { 'do_normalize': False, 'do_resize': True, 'image_processor_type': 'ViTImageProcessor', 'resample': 3, 'size': {'height': 32, 'width': 128}, } __snake_case : Dict = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : str , **__a : Any ) -> str: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] , **__a : Any ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : str ) -> Dict: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : int ) -> Dict: '''simple docstring''' __snake_case : List[Any] = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __snake_case : Dict = Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) return image_input def A_ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = self.get_tokenizer() __snake_case : List[str] = self.get_image_processor() __snake_case : Optional[int] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Union[str, Any] = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__a ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : str = self.get_tokenizer() __snake_case : Optional[Any] = self.get_image_processor() __snake_case : Optional[int] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : str = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Any = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[Any] = self.get_image_processor() __snake_case : Optional[Any] = self.get_tokenizer() __snake_case : Optional[Any] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Any = image_processor(__a , return_tensors='np' ) __snake_case : Optional[int] = processor(images=__a , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : int ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : List[Any] = self.get_tokenizer() __snake_case : int = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Tuple = 'test' __snake_case : Tuple = processor(text=__a ) __snake_case : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : int ) -> Dict: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Optional[int] = self.get_tokenizer() __snake_case : Optional[Any] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Dict = 'test' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Optional[Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'labels'] ) # test if it raises when no input is passed with pytest.raises(__a ): processor() def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.get_image_processor() __snake_case : Optional[Any] = self.get_tokenizer() __snake_case : Tuple = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __snake_case : List[Any] = processor.char_decode(__a ) __snake_case : Any = tokenizer.batch_decode(__a ) __snake_case : List[Any] = [seq.replace(' ' , '' ) for seq in decoded_tok] self.assertListEqual(__a , __a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Optional[Any] = self.get_tokenizer() __snake_case : Union[str, Any] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = None __snake_case : List[Any] = self.prepare_image_inputs() __snake_case : Optional[Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Optional[int] = MgpstrProcessor(tokenizer=__a , image_processor=__a ) __snake_case : str = torch.randn(1 , 27 , 38 ) __snake_case : int = torch.randn(1 , 27 , 50257 ) __snake_case : Optional[int] = torch.randn(1 , 27 , 30522 ) __snake_case : Tuple = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'] )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
1
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __get__( self : Optional[Any] , __a : List[str] , __a : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError('unreadable attribute' ) __snake_case : Tuple = '__cached_' + self.fget.__name__ __snake_case : int = getattr(__a , __a , __a ) if cached is None: __snake_case : Optional[int] = self.fget(__a ) setattr(__a , __a , __a ) return cached def a_ ( _UpperCAmelCase : int ) -> List[Any]: __snake_case : int = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'''invalid truth value {val!r}''' ) def a_ ( _UpperCAmelCase : List[Any] ) -> str: if is_torch_fx_proxy(_UpperCAmelCase ): return True if is_torch_available(): import torch if isinstance(_UpperCAmelCase ,torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(_UpperCAmelCase ,tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(_UpperCAmelCase ,(jnp.ndarray, Tracer) ): return True return isinstance(_UpperCAmelCase ,np.ndarray ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> List[Any]: return isinstance(_UpperCAmelCase ,np.ndarray ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: return _is_numpy(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[str] ) -> List[Any]: import torch return isinstance(_UpperCAmelCase ,torch.Tensor ) def a_ ( _UpperCAmelCase : List[Any] ) -> List[Any]: return False if not is_torch_available() else _is_torch(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: import torch return isinstance(_UpperCAmelCase ,torch.device ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: return False if not is_torch_available() else _is_torch_device(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[Any] ) -> Any: import torch if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): if hasattr(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : int = getattr(_UpperCAmelCase ,_UpperCAmelCase ) else: return False return isinstance(_UpperCAmelCase ,torch.dtype ) def a_ ( _UpperCAmelCase : str ) -> Optional[int]: return False if not is_torch_available() else _is_torch_dtype(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Tuple: import tensorflow as tf return isinstance(_UpperCAmelCase ,tf.Tensor ) def a_ ( _UpperCAmelCase : Tuple ) -> str: return False if not is_tf_available() else _is_tensorflow(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Any: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(_UpperCAmelCase ,'is_symbolic_tensor' ): return tf.is_symbolic_tensor(_UpperCAmelCase ) return type(_UpperCAmelCase ) == tf.Tensor def a_ ( _UpperCAmelCase : List[Any] ) -> Union[str, Any]: return False if not is_tf_available() else _is_tf_symbolic_tensor(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import jax.numpy as jnp # noqa: F811 return isinstance(_UpperCAmelCase ,jnp.ndarray ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: return False if not is_flax_available() else _is_jax(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> List[Any]: if isinstance(_UpperCAmelCase ,(dict, UserDict) ): return {k: to_py_obj(_UpperCAmelCase ) for k, v in obj.items()} elif isinstance(_UpperCAmelCase ,(list, tuple) ): return [to_py_obj(_UpperCAmelCase ) for o in obj] elif is_tf_tensor(_UpperCAmelCase ): return obj.numpy().tolist() elif is_torch_tensor(_UpperCAmelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(_UpperCAmelCase ): return np.asarray(_UpperCAmelCase ).tolist() elif isinstance(_UpperCAmelCase ,(np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def a_ ( _UpperCAmelCase : Any ) -> Any: if isinstance(_UpperCAmelCase ,(dict, UserDict) ): return {k: to_numpy(_UpperCAmelCase ) for k, v in obj.items()} elif isinstance(_UpperCAmelCase ,(list, tuple) ): return np.array(_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): return obj.numpy() elif is_torch_tensor(_UpperCAmelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(_UpperCAmelCase ): return np.asarray(_UpperCAmelCase ) else: return obj class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : Dict = fields(self ) # Safety and consistency checks if not len(__a ): raise ValueError(f'''{self.__class__.__name__} has no fields.''' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''' ) __snake_case : Dict = getattr(self , class_fields[0].name ) __snake_case : Any = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__a ): if isinstance(__a , __a ): __snake_case : Optional[int] = first_field.items() __snake_case : List[Any] = True else: try: __snake_case : Optional[int] = iter(__a ) __snake_case : List[str] = True except TypeError: __snake_case : Optional[int] = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(__a ): if ( not isinstance(__a , (list, tuple) ) or not len(__a ) == 2 or not isinstance(element[0] , __a ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute __snake_case : Union[str, Any] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: __snake_case : Optional[int] = element[1] elif first_field is not None: __snake_case : Optional[int] = first_field else: for field in class_fields: __snake_case : Optional[Any] = getattr(self , field.name ) if v is not None: __snake_case : List[str] = v def __delitem__( self : List[str] , *__a : Dict , **__a : Union[str, Any] ) -> Tuple: '''simple docstring''' raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Optional[int] , *__a : List[Any] , **__a : Any ) -> Union[str, Any]: '''simple docstring''' raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Union[str, Any] , *__a : Dict , **__a : Any ) -> Dict: '''simple docstring''' raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Dict , *__a : str , **__a : str ) -> Dict: '''simple docstring''' raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''' ) def __getitem__( self : str , __a : Any ) -> int: '''simple docstring''' if isinstance(__a , __a ): __snake_case : List[Any] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : List[Any] , __a : Union[str, Any] , __a : List[Any] ) -> int: '''simple docstring''' if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__a , __a ) super().__setattr__(__a , __a ) def __setitem__( self : List[Any] , __a : Optional[Any] , __a : Any ) -> int: '''simple docstring''' # Will raise a KeyException if needed super().__setitem__(__a , __a ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__a , __a ) def A_ ( self : Dict ) -> Tuple[Any]: '''simple docstring''' return tuple(self[k] for k in self.keys() ) class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : List[str] , __a : List[Any] ) -> Dict: '''simple docstring''' raise ValueError( f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}''' ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''longest''' A__ = '''max_length''' A__ = '''do_not_pad''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''pt''' A__ = '''tf''' A__ = '''np''' A__ = '''jax''' class snake_case__ : def __init__( self : Union[str, Any] , __a : List[ContextManager] ) -> List[str]: '''simple docstring''' __snake_case : Tuple = context_managers __snake_case : Optional[int] = ExitStack() def __enter__( self : List[str] ) -> Optional[Any]: '''simple docstring''' for context_manager in self.context_managers: self.stack.enter_context(__a ) def __exit__( self : Tuple , *__a : Any , **__a : Any ) -> List[Any]: '''simple docstring''' self.stack.__exit__(*__a , **__a ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: __snake_case : Any = infer_framework(_UpperCAmelCase ) if framework == "tf": __snake_case : Optional[int] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __snake_case : Any = inspect.signature(model_class.forward ) # PyTorch models else: __snake_case : Optional[Any] = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def a_ ( _UpperCAmelCase : Any ) -> Dict: __snake_case : str = model_class.__name__ __snake_case : str = infer_framework(_UpperCAmelCase ) if framework == "tf": __snake_case : Optional[Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __snake_case : List[str] = inspect.signature(model_class.forward ) # PyTorch models else: __snake_case : Dict = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def a_ ( _UpperCAmelCase : MutableMapping ,_UpperCAmelCase : str = "" ,_UpperCAmelCase : str = "." ) -> int: def _flatten_dict(_UpperCAmelCase : Tuple ,_UpperCAmelCase : str="" ,_UpperCAmelCase : Dict="." ): for k, v in d.items(): __snake_case : str = str(_UpperCAmelCase ) + delimiter + str(_UpperCAmelCase ) if parent_key else k if v and isinstance(_UpperCAmelCase ,_UpperCAmelCase ): yield from flatten_dict(_UpperCAmelCase ,_UpperCAmelCase ,delimiter=_UpperCAmelCase ).items() else: yield key, v return dict(_flatten_dict(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) @contextmanager def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : bool = False ) -> List[Any]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Tuple=None ) -> Any: if is_numpy_array(_UpperCAmelCase ): return np.transpose(_UpperCAmelCase ,axes=_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.T if axes is None else array.permute(*_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.transpose(_UpperCAmelCase ,perm=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.transpose(_UpperCAmelCase ,axes=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for transpose: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Any ) -> int: if is_numpy_array(_UpperCAmelCase ): return np.reshape(_UpperCAmelCase ,_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.reshape(*_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.reshape(_UpperCAmelCase ,_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.reshape(_UpperCAmelCase ,_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for reshape: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ) -> Optional[int]: if is_numpy_array(_UpperCAmelCase ): return np.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.squeeze() if axis is None else array.squeeze(dim=_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for squeeze: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ) -> Any: if is_numpy_array(_UpperCAmelCase ): return np.expand_dims(_UpperCAmelCase ,_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.unsqueeze(dim=_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.expand_dims(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.expand_dims(_UpperCAmelCase ,axis=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for expand_dims: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: if is_numpy_array(_UpperCAmelCase ): return np.size(_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.numel() elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.size(_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return array.size else: raise ValueError(f'''Type not supported for expand_dims: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Any ) -> Dict: for key, value in auto_map.items(): if isinstance(_UpperCAmelCase ,(tuple, list) ): __snake_case : Any = [f'''{repo_id}--{v}''' if (v is not None and '--' not in v) else v for v in value] elif value is not None and "--" not in value: __snake_case : List[Any] = f'''{repo_id}--{value}''' return auto_map def a_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: for base_class in inspect.getmro(_UpperCAmelCase ): __snake_case : Optional[Any] = base_class.__module__ __snake_case : Optional[int] = base_class.__name__ if module.startswith('tensorflow' ) or module.startswith('keras' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('torch' ) or name == "PreTrainedModel": return "pt" elif module.startswith('flax' ) or module.startswith('jax' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'''Could not infer framework from class {model_class}.''' )
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
1
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING A__ : Optional[int] = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Dict , **__a : Dict ) -> List[str]: '''simple docstring''' super().__init__(**__a ) if self.framework == "tf": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) requires_backends(self , 'vision' ) self.check_model_type(__a ) def __call__( self : Dict , __a : Union[str, "Image.Image", List[Dict[str, Any]]] , __a : Union[str, List[str]] = None , **__a : Any , ) -> str: '''simple docstring''' if "text_queries" in kwargs: __snake_case : Tuple = kwargs.pop('text_queries' ) if isinstance(__a , (str, Image.Image) ): __snake_case : List[str] = {'image': image, 'candidate_labels': candidate_labels} else: __snake_case : Optional[int] = image __snake_case : Union[str, Any] = super().__call__(__a , **__a ) return results def A_ ( self : List[str] , **__a : int ) -> Optional[int]: '''simple docstring''' __snake_case : str = {} if "threshold" in kwargs: __snake_case : int = kwargs['threshold'] if "top_k" in kwargs: __snake_case : int = kwargs['top_k'] return {}, {}, postprocess_params def A_ ( self : List[str] , __a : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Tuple = load_image(inputs['image'] ) __snake_case : Optional[int] = inputs['candidate_labels'] if isinstance(__a , __a ): __snake_case : Dict = candidate_labels.split(',' ) __snake_case : Tuple = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(__a ): __snake_case : str = self.tokenizer(__a , return_tensors=self.framework ) __snake_case : Tuple = self.image_processor(__a , return_tensors=self.framework ) yield { "is_last": i == len(__a ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def A_ ( self : Optional[Any] , __a : Optional[int] ) -> Optional[int]: '''simple docstring''' __snake_case : Any = model_inputs.pop('target_size' ) __snake_case : Tuple = model_inputs.pop('candidate_label' ) __snake_case : List[Any] = model_inputs.pop('is_last' ) __snake_case : Any = self.model(**__a ) __snake_case : Optional[int] = {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs} return model_outputs def A_ ( self : Union[str, Any] , __a : Optional[Any] , __a : List[Any]=0.1 , __a : Dict=None ) -> Optional[Any]: '''simple docstring''' __snake_case : str = [] for model_output in model_outputs: __snake_case : Optional[Any] = model_output['candidate_label'] __snake_case : List[str] = BaseModelOutput(__a ) __snake_case : Optional[int] = self.image_processor.post_process_object_detection( outputs=__a , threshold=__a , target_sizes=model_output['target_size'] )[0] for index in outputs["scores"].nonzero(): __snake_case : Dict = outputs['scores'][index].item() __snake_case : List[Any] = self._get_bounding_box(outputs['boxes'][index][0] ) __snake_case : Any = {'score': score, 'label': label, 'box': box} results.append(__a ) __snake_case : str = sorted(__a , key=lambda __a : x["score"] , reverse=__a ) if top_k: __snake_case : Any = results[:top_k] return results def A_ ( self : Optional[int] , __a : "torch.Tensor" ) -> Dict[str, int]: '''simple docstring''' if self.framework != "pt": raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.' ) __snake_case , __snake_case , __snake_case , __snake_case : Dict = box.int().tolist() __snake_case : str = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
1
'''simple docstring''' A__ : Optional[Any] = tuple[float, float, float] A__ : str = tuple[float, float, float] def a_ ( _UpperCAmelCase : Pointad ,_UpperCAmelCase : Pointad ) -> Vectorad: __snake_case : List[Any] = end_pointa[0] - end_pointa[0] __snake_case : str = end_pointa[1] - end_pointa[1] __snake_case : Optional[int] = end_pointa[2] - end_pointa[2] return (x, y, z) def a_ ( _UpperCAmelCase : Vectorad ,_UpperCAmelCase : Vectorad ) -> Vectorad: __snake_case : Dict = ab[1] * ac[2] - ab[2] * ac[1] # *i __snake_case : int = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j __snake_case : Any = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def a_ ( _UpperCAmelCase : Vectorad ,_UpperCAmelCase : int ) -> bool: return tuple(round(_UpperCAmelCase ,_UpperCAmelCase ) for x in vector ) == (0, 0, 0) def a_ ( _UpperCAmelCase : Pointad ,_UpperCAmelCase : Pointad ,_UpperCAmelCase : Pointad ,_UpperCAmelCase : int = 10 ) -> bool: __snake_case : Any = create_vector(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : List[Any] = create_vector(_UpperCAmelCase ,_UpperCAmelCase ) return is_zero_vector(get_ad_vectors_cross(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase )
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' import math import tensorflow as tf from packaging import version def a_ ( _UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: __snake_case : Optional[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : str = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) ,x.dtype ) )) return x * cdf def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : Dict = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : List[Any] = tf.cast(math.pi ,x.dtype ) __snake_case : List[str] = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) __snake_case : Optional[Any] = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(_UpperCAmelCase ,3 )) )) return x * cdf def a_ ( _UpperCAmelCase : Optional[int] ) -> Optional[Any]: __snake_case : Any = tf.convert_to_tensor(_UpperCAmelCase ) return x * tf.tanh(tf.math.softplus(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : str ) -> Dict: __snake_case : Optional[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : List[Any] = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) __snake_case : List[str] = tf.cast(0.7_9_7_8_8_4_5_6_0_8 ,x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def a_ ( _UpperCAmelCase : Dict ) -> Optional[int]: __snake_case : List[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : str = tf.cast(1.7_0_2 ,x.dtype ) return x * tf.math.sigmoid(coeff * x ) def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: return tf.clip_by_value(_gelu(_UpperCAmelCase ) ,-10 ,10 ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str=-1 ) -> Dict: __snake_case , __snake_case : Dict = tf.split(_UpperCAmelCase ,2 ,axis=_UpperCAmelCase ) return a * tf.math.sigmoid(_UpperCAmelCase ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def a_ ( _UpperCAmelCase : int ) -> Dict: return tf.keras.activations.gelu(_UpperCAmelCase ,approximate=_UpperCAmelCase ) A__ : List[Any] = tf.keras.activations.gelu A__ : str = approximate_gelu_wrap else: A__ : List[str] = _gelu A__ : List[str] = _gelu_new A__ : str = { '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def a_ ( _UpperCAmelCase : int ) -> int: if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) A__ : List[Any] = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any] = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any] = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys A__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
'''simple docstring''' import os from datetime import datetime as dt from github import Github A__ : Union[str, Any] = [ '''good first issue''', '''feature request''', '''wip''', ] def a_ ( ) -> Optional[int]: __snake_case : List[str] = Github(os.environ['GITHUB_TOKEN'] ) __snake_case : Any = g.get_repo('huggingface/accelerate' ) __snake_case : List[Any] = repo.get_issues(state='open' ) for issue in open_issues: __snake_case : Tuple = sorted([comment for comment in issue.get_comments()] ,key=lambda _UpperCAmelCase : i.created_at ,reverse=_UpperCAmelCase ) __snake_case : Tuple = comments[0] if len(_UpperCAmelCase ) > 0 else None __snake_case : Dict = dt.utcnow() __snake_case : Dict = (current_time - issue.updated_at).days __snake_case : str = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state='closed' ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
0
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
1
'''simple docstring''' import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() A__ : Tuple = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : str ) -> Any: __snake_case : str = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __snake_case : str = 1_28 elif "12-12" in model_name: __snake_case : str = 12 __snake_case : List[str] = 12 elif "14-14" in model_name: __snake_case : Union[str, Any] = 14 __snake_case : Dict = 14 elif "16-16" in model_name: __snake_case : int = 16 __snake_case : List[Any] = 16 else: raise ValueError('Model not supported' ) __snake_case : Optional[Any] = 'huggingface/label-files' if "speech-commands" in model_name: __snake_case : Optional[int] = 35 __snake_case : Union[str, Any] = 'speech-commands-v2-id2label.json' else: __snake_case : Union[str, Any] = 5_27 __snake_case : Tuple = 'audioset-id2label.json' __snake_case : Optional[int] = json.load(open(hf_hub_download(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ,'r' ) ) __snake_case : int = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Tuple = idalabel __snake_case : int = {v: k for k, v in idalabel.items()} return config def a_ ( _UpperCAmelCase : Union[str, Any] ) -> List[str]: if "module.v" in name: __snake_case : str = name.replace('module.v' ,'audio_spectrogram_transformer' ) if "cls_token" in name: __snake_case : List[Any] = name.replace('cls_token' ,'embeddings.cls_token' ) if "dist_token" in name: __snake_case : List[Any] = name.replace('dist_token' ,'embeddings.distillation_token' ) if "pos_embed" in name: __snake_case : Optional[int] = name.replace('pos_embed' ,'embeddings.position_embeddings' ) if "patch_embed.proj" in name: __snake_case : List[Any] = name.replace('patch_embed.proj' ,'embeddings.patch_embeddings.projection' ) # transformer blocks if "blocks" in name: __snake_case : Dict = name.replace('blocks' ,'encoder.layer' ) if "attn.proj" in name: __snake_case : Tuple = name.replace('attn.proj' ,'attention.output.dense' ) if "attn" in name: __snake_case : Dict = name.replace('attn' ,'attention.self' ) if "norm1" in name: __snake_case : Dict = name.replace('norm1' ,'layernorm_before' ) if "norm2" in name: __snake_case : List[str] = name.replace('norm2' ,'layernorm_after' ) if "mlp.fc1" in name: __snake_case : Union[str, Any] = name.replace('mlp.fc1' ,'intermediate.dense' ) if "mlp.fc2" in name: __snake_case : Optional[int] = name.replace('mlp.fc2' ,'output.dense' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __snake_case : int = name.replace('audio_spectrogram_transformer.norm' ,'audio_spectrogram_transformer.layernorm' ) # classifier head if "module.mlp_head.0" in name: __snake_case : Union[str, Any] = name.replace('module.mlp_head.0' ,'classifier.layernorm' ) if "module.mlp_head.1" in name: __snake_case : Tuple = name.replace('module.mlp_head.1' ,'classifier.dense' ) return name def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Any ) -> int: for key in orig_state_dict.copy().keys(): __snake_case : int = orig_state_dict.pop(_UpperCAmelCase ) if "qkv" in key: __snake_case : Union[str, Any] = key.split('.' ) __snake_case : int = int(key_split[3] ) __snake_case : Union[str, Any] = config.hidden_size if "weight" in key: __snake_case : Optional[Any] = val[:dim, :] __snake_case : Optional[int] = val[dim : dim * 2, :] __snake_case : Any = val[-dim:, :] else: __snake_case : int = val[:dim] __snake_case : Optional[Any] = val[dim : dim * 2] __snake_case : str = val[-dim:] else: __snake_case : int = val return orig_state_dict def a_ ( _UpperCAmelCase : Dict ) -> Optional[int]: __snake_case : List[Any] = [ 'module.v.head.weight', 'module.v.head.bias', 'module.v.head_dist.weight', 'module.v.head_dist.bias', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase ,_UpperCAmelCase ) @torch.no_grad() def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Dict=False ) -> List[str]: __snake_case : Dict = get_audio_spectrogram_transformer_config(_UpperCAmelCase ) __snake_case : Union[str, Any] = { 'ast-finetuned-audioset-10-10-0.4593': ( 'https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.450': ( 'https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.448': ( 'https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.448-v2': ( 'https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1' ), 'ast-finetuned-audioset-12-12-0.447': ( 'https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1' ), 'ast-finetuned-audioset-14-14-0.443': ( 'https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1' ), 'ast-finetuned-audioset-16-16-0.442': ( 'https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1' ), 'ast-finetuned-speech-commands-v2': ( 'https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1' ), } # load original state_dict __snake_case : Any = model_name_to_url[model_name] __snake_case : Dict = torch.hub.load_state_dict_from_url(_UpperCAmelCase ,map_location='cpu' ) # remove some keys remove_keys(_UpperCAmelCase ) # rename some keys __snake_case : List[Any] = convert_state_dict(_UpperCAmelCase ,_UpperCAmelCase ) # load 🤗 model __snake_case : Any = ASTForAudioClassification(_UpperCAmelCase ) model.eval() model.load_state_dict(_UpperCAmelCase ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __snake_case : Dict = -4.2_6_7_7_3_9_3 if 'speech-commands' not in model_name else -6.8_4_5_9_7_8 __snake_case : Dict = 4.5_6_8_9_9_7_4 if 'speech-commands' not in model_name else 5.5_6_5_4_5_2_6 __snake_case : Tuple = 10_24 if 'speech-commands' not in model_name else 1_28 __snake_case : Tuple = ASTFeatureExtractor(mean=_UpperCAmelCase ,std=_UpperCAmelCase ,max_length=_UpperCAmelCase ) if "speech-commands" in model_name: __snake_case : int = load_dataset('speech_commands' ,'v0.02' ,split='validation' ) __snake_case : Optional[int] = dataset[0]['audio']['array'] else: __snake_case : List[str] = hf_hub_download( repo_id='nielsr/audio-spectogram-transformer-checkpoint' ,filename='sample_audio.flac' ,repo_type='dataset' ,) __snake_case , __snake_case : Optional[int] = torchaudio.load(_UpperCAmelCase ) __snake_case : Union[str, Any] = waveform.squeeze().numpy() __snake_case : Optional[Any] = feature_extractor(_UpperCAmelCase ,sampling_rate=1_60_00 ,return_tensors='pt' ) # forward pass __snake_case : Any = model(**_UpperCAmelCase ) __snake_case : str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __snake_case : Tuple = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __snake_case : Union[str, Any] = torch.tensor([-1.1_9_8_6, -7.0_9_0_3, -8.2_7_1_8] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __snake_case : Dict = torch.tensor([-2.6_1_2_8, -8.0_0_8_0, -9.4_3_4_4] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __snake_case : Optional[Any] = torch.tensor([-1.5_0_8_0, -7.4_5_3_4, -8.8_9_1_7] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __snake_case : List[Any] = torch.tensor([-0.5_0_5_0, -6.5_8_3_3, -8.0_8_4_3] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __snake_case : Optional[int] = torch.tensor([-0.3_8_2_6, -7.0_3_3_6, -8.2_4_1_3] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __snake_case : List[Any] = torch.tensor([-1.2_1_1_3, -6.9_1_0_1, -8.3_4_7_0] ) elif model_name == "ast-finetuned-speech-commands-v2": __snake_case : Dict = torch.tensor([6.1_5_8_9, -8.0_5_6_6, -8.7_9_8_4] ) else: raise ValueError('Unknown model name' ) if not torch.allclose(logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ): raise ValueError('Logits don\'t match' ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCAmelCase ) print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(_UpperCAmelCase ) if push_to_hub: print('Pushing model and feature extractor to the hub...' ) model.push_to_hub(f'''MIT/{model_name}''' ) feature_extractor.push_to_hub(f'''MIT/{model_name}''' ) if __name__ == "__main__": A__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''ast-finetuned-audioset-10-10-0.4593''', type=str, help='''Name of the Audio Spectrogram Transformer model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) A__ : Dict = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
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 ViTImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : Optional[Any] , __a : str , __a : int=13 , __a : List[str]=3 , __a : int=224 , __a : str=30 , __a : Tuple=400 , __a : int=True , __a : Any=None , __a : List[str]=True , __a : Optional[Any]=[0.5, 0.5, 0.5] , __a : List[Any]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = size if size is not None else {'height': 18, 'width': 18} __snake_case : List[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : str = num_channels __snake_case : List[Any] = image_size __snake_case : Optional[Any] = min_resolution __snake_case : Optional[Any] = max_resolution __snake_case : Dict = do_resize __snake_case : Union[str, Any] = size __snake_case : List[Any] = do_normalize __snake_case : List[str] = image_mean __snake_case : Any = image_std def A_ ( self : Optional[int] ) -> str: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ViTImageProcessor if is_vision_available() else None def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' __snake_case : Optional[Any] = EfficientFormerImageProcessorTester(self ) @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def A_ ( self : Tuple ) -> int: '''simple docstring''' __snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'image_mean' ) ) self.assertTrue(hasattr(__a , 'image_std' ) ) self.assertTrue(hasattr(__a , 'do_normalize' ) ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) def A_ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' pass def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # Initialize image_processor __snake_case : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __snake_case : int = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __snake_case : int = image_processor(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' # Initialize image_processor __snake_case : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : List[str] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __snake_case : Optional[Any] = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processor(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def A_ ( self : int ) -> Optional[Any]: '''simple docstring''' # Initialize image_processor __snake_case : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __snake_case : List[str] = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __snake_case : str = image_processor(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , )
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __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 A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 10_00 ) -> int: __snake_case : Tuple = 2**power __snake_case : List[str] = str(_UpperCAmelCase ) __snake_case : Union[str, Any] = list(_UpperCAmelCase ) __snake_case : Optional[Any] = 0 for i in list_num: sum_of_num += int(_UpperCAmelCase ) return sum_of_num if __name__ == "__main__": A__ : List[Any] = int(input('''Enter the power of 2: ''').strip()) print('''2 ^ ''', power, ''' = ''', 2**power) A__ : Dict = solution(power) print('''Sum of the digits is: ''', result)
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging A__ : Union[str, Any] = logging.get_logger(__name__) A__ : int = { '''Visual-Attention-Network/van-base''': ( '''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json''' ), } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''van''' def __init__( self : Any , __a : int=224 , __a : Union[str, Any]=3 , __a : Union[str, Any]=[7, 3, 3, 3] , __a : Any=[4, 2, 2, 2] , __a : Union[str, Any]=[64, 128, 320, 512] , __a : List[str]=[3, 3, 12, 3] , __a : Optional[int]=[8, 8, 4, 4] , __a : Dict="gelu" , __a : Dict=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Union[str, Any]=1e-2 , __a : List[str]=0.0 , __a : Optional[Any]=0.0 , **__a : List[str] , ) -> str: '''simple docstring''' super().__init__(**__a ) __snake_case : str = image_size __snake_case : str = num_channels __snake_case : Optional[Any] = patch_sizes __snake_case : Dict = strides __snake_case : Tuple = hidden_sizes __snake_case : List[str] = depths __snake_case : List[Any] = mlp_ratios __snake_case : Tuple = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : str = layer_norm_eps __snake_case : List[str] = layer_scale_init_value __snake_case : Optional[int] = drop_path_rate __snake_case : Union[str, Any] = dropout_rate
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(_UpperCAmelCase ,2 ) - pow(_UpperCAmelCase ,2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_UpperCAmelCase ,2 ) - pow(_UpperCAmelCase ,2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_UpperCAmelCase ,2 ) + pow(_UpperCAmelCase ,2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
1
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL A__ : Union[str, Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : tuple ,_UpperCAmelCase : Path ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : str=False ,) -> Dict: output_path.parent.mkdir(parents=_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( _UpperCAmelCase ,_UpperCAmelCase ,f=output_path.as_posix() ,input_names=_UpperCAmelCase ,output_names=_UpperCAmelCase ,dynamic_axes=_UpperCAmelCase ,do_constant_folding=_UpperCAmelCase ,use_external_data_format=_UpperCAmelCase ,enable_onnx_checker=_UpperCAmelCase ,opset_version=_UpperCAmelCase ,) else: export( _UpperCAmelCase ,_UpperCAmelCase ,f=output_path.as_posix() ,input_names=_UpperCAmelCase ,output_names=_UpperCAmelCase ,dynamic_axes=_UpperCAmelCase ,do_constant_folding=_UpperCAmelCase ,opset_version=_UpperCAmelCase ,) @torch.no_grad() def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ,_UpperCAmelCase : int ,_UpperCAmelCase : bool = False ) -> List[Any]: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __snake_case : Union[str, Any] = 'cuda' elif fpaa and not torch.cuda.is_available(): raise ValueError('`float16` model export is only supported on GPUs with CUDA' ) else: __snake_case : List[str] = 'cpu' __snake_case : List[Any] = Path(_UpperCAmelCase ) # VAE DECODER __snake_case : Optional[int] = AutoencoderKL.from_pretrained(model_path + '/vae' ) __snake_case : Any = vae_decoder.config.latent_channels # forward only through the decoder part __snake_case : str = vae_decoder.decode onnx_export( _UpperCAmelCase ,model_args=( torch.randn(1 ,_UpperCAmelCase ,25 ,25 ).to(device=_UpperCAmelCase ,dtype=_UpperCAmelCase ), False, ) ,output_path=output_path / 'vae_decoder' / 'model.onnx' ,ordered_input_names=['latent_sample', 'return_dict'] ,output_names=['sample'] ,dynamic_axes={ 'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } ,opset=_UpperCAmelCase ,) del vae_decoder if __name__ == "__main__": A__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') A__ : int = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('''SD: Done: ONNX''')
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
1
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case__ : def __init__( self : Tuple , __a : int , __a : Optional[Any]=13 , __a : Optional[Any]=7 , __a : Dict=True , __a : Optional[Any]=True , __a : Any=True , __a : Optional[int]=True , __a : Tuple=True , __a : Any=False , __a : int=False , __a : Dict=False , __a : Optional[int]=2 , __a : Optional[Any]=99 , __a : Tuple=0 , __a : str=32 , __a : List[Any]=5 , __a : List[Any]=4 , __a : Optional[int]=0.1 , __a : List[str]=0.1 , __a : Dict=512 , __a : str=2 , __a : List[str]=0.0_2 , __a : Any=2 , __a : str=4 , __a : int="last" , __a : Any=True , __a : Optional[int]=None , __a : Tuple=0 , ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = parent __snake_case : Any = batch_size __snake_case : Optional[Any] = seq_length __snake_case : List[str] = is_training __snake_case : Tuple = use_input_lengths __snake_case : List[Any] = use_token_type_ids __snake_case : Optional[Any] = use_labels __snake_case : List[Any] = gelu_activation __snake_case : List[Any] = sinusoidal_embeddings __snake_case : Any = causal __snake_case : str = asm __snake_case : int = n_langs __snake_case : int = vocab_size __snake_case : Tuple = n_special __snake_case : Optional[Any] = hidden_size __snake_case : str = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Any = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : Union[str, Any] = max_position_embeddings __snake_case : List[str] = type_sequence_label_size __snake_case : Optional[Any] = initializer_range __snake_case : Dict = num_labels __snake_case : Dict = num_choices __snake_case : Dict = summary_type __snake_case : Dict = use_proj __snake_case : List[str] = scope __snake_case : Optional[int] = bos_token_id def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' __snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : Optional[int] = None if self.use_input_lengths: __snake_case : Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __snake_case : int = None if self.use_token_type_ids: __snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __snake_case : List[Any] = None __snake_case : str = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size] , 2 ).float() __snake_case : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __snake_case : str = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def A_ ( self : Optional[Any] , __a : Dict , __a : Tuple , __a : str , __a : Dict , __a : Optional[Any] , __a : str , __a : List[Any] , __a : int , __a : Tuple , ) -> str: '''simple docstring''' __snake_case : Optional[int] = XLMModel(config=__a ) model.to(__a ) model.eval() __snake_case : Optional[int] = model(__a , lengths=__a , langs=__a ) __snake_case : Dict = model(__a , langs=__a ) __snake_case : Union[str, Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : Any , __a : List[Any] , __a : List[str] , __a : Optional[Any] , __a : str , __a : int , __a : Union[str, Any] , __a : str , __a : Dict , __a : str , ) -> List[Any]: '''simple docstring''' __snake_case : str = XLMWithLMHeadModel(__a ) model.to(__a ) model.eval() __snake_case : Union[str, Any] = model(__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self : List[str] , __a : str , __a : Tuple , __a : Optional[int] , __a : Any , __a : Optional[Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : int , __a : List[str] , ) -> int: '''simple docstring''' __snake_case : Any = XLMForQuestionAnsweringSimple(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a ) __snake_case : List[str] = model(__a , start_positions=__a , end_positions=__a ) __snake_case : Any = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A_ ( self : str , __a : List[Any] , __a : Optional[Any] , __a : Any , __a : Union[str, Any] , __a : Dict , __a : Any , __a : str , __a : Tuple , __a : int , ) -> List[str]: '''simple docstring''' __snake_case : int = XLMForQuestionAnswering(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a ) __snake_case : Tuple = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , p_mask=__a , ) __snake_case : Tuple = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , ) ((__snake_case) , ) : Optional[int] = result_with_labels.to_tuple() __snake_case : Tuple = model(__a , start_positions=__a , end_positions=__a ) ((__snake_case) , ) : Optional[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def A_ ( self : Union[str, Any] , __a : Union[str, Any] , __a : List[str] , __a : int , __a : Tuple , __a : Any , __a : List[Any] , __a : Tuple , __a : List[str] , __a : Tuple , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = XLMForSequenceClassification(__a ) model.to(__a ) model.eval() __snake_case : Dict = model(__a ) __snake_case : Dict = model(__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A_ ( self : Dict , __a : List[str] , __a : Any , __a : List[str] , __a : Dict , __a : str , __a : Tuple , __a : Optional[Any] , __a : List[Any] , __a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = self.num_labels __snake_case : Any = XLMForTokenClassification(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A_ ( self : List[str] , __a : Optional[Any] , __a : Tuple , __a : Dict , __a : Optional[Any] , __a : Any , __a : List[Any] , __a : str , __a : Optional[Any] , __a : Optional[int] , ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.num_choices __snake_case : str = XLMForMultipleChoice(config=__a ) model.to(__a ) model.eval() __snake_case : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Dict = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A_ ( self : int ) -> str: '''simple docstring''' __snake_case : List[Any] = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : Optional[Any] = config_and_inputs __snake_case : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) A__ = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable A__ = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def A_ ( self : Optional[int] , __a : Tuple , __a : Optional[int] , __a : List[str] , __a : List[Any] , __a : Any ) -> List[Any]: '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def A_ ( self : List[Any] , __a : Any , __a : Optional[Any] , __a : Any=False ) -> Tuple: '''simple docstring''' __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __snake_case : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) __snake_case : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def A_ ( self : Dict ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = XLMModelTester(self ) __snake_case : List[str] = ConfigTester(self , config_class=__a , emb_dim=37 ) def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : int ) -> Optional[Any]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*__a ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' __snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*__a ) def A_ ( self : Dict ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*__a ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*__a ) def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*__a ) def A_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*__a ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*__a ) def A_ ( self : int , __a : Union[str, Any] , __a : int , __a : int , __a : Optional[Any] , __a : Any , __a : Optional[Any]=False , __a : Union[str, Any]=1 ) -> Optional[Any]: '''simple docstring''' self.assertIsInstance(__a , __a ) self.assertListEqual( [isinstance(__a , __a ) for iter_attentions in attentions] , [True] * len(__a ) ) self.assertEqual(len(__a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(__a ): # adds PAD dummy token __snake_case : Tuple = min_length + idx + 1 __snake_case : Optional[Any] = min_length + idx + 1 __snake_case : Optional[Any] = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__a ) ) def A_ ( self : Optional[Any] , __a : List[str] , __a : Dict , __a : Optional[Any] , __a : List[str] , __a : List[str] , __a : List[str]=False , __a : Any=1 ) -> List[str]: '''simple docstring''' self.assertIsInstance(__a , __a ) self.assertListEqual( [isinstance(__a , __a ) for iter_hidden_states in hidden_states] , [True] * len(__a ) , ) self.assertEqual(len(__a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(__a ): # adds PAD dummy token __snake_case : Optional[Any] = min_length + idx + 1 __snake_case : List[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__a ) , ) pass @slow def A_ ( self : str ) -> str: '''simple docstring''' for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = XLMModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch class snake_case__ ( unittest.TestCase ): @slow def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(__a ) __snake_case : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=__a ) # the president __snake_case : List[str] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference __snake_case : int = model.generate(__a , do_sample=__a ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __a )
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ : def __init__( self : str , __a : Optional[int] , __a : str=3 , __a : Optional[int]=32 , __a : Optional[Any]=3 , __a : Optional[int]=10 , __a : List[Any]=[10, 20, 30, 40] , __a : Dict=[1, 1, 2, 1] , __a : Tuple=True , __a : Union[str, Any]=True , __a : Dict="relu" , __a : Any=3 , __a : str=None , ) -> int: '''simple docstring''' __snake_case : str = parent __snake_case : Union[str, Any] = batch_size __snake_case : List[str] = image_size __snake_case : Tuple = num_channels __snake_case : Any = embeddings_size __snake_case : List[Any] = hidden_sizes __snake_case : str = depths __snake_case : int = is_training __snake_case : List[str] = use_labels __snake_case : Tuple = hidden_act __snake_case : Any = num_labels __snake_case : List[str] = scope __snake_case : Dict = len(__a ) def A_ ( self : int ) -> Optional[int]: '''simple docstring''' __snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : str = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def A_ ( self : Optional[Any] , __a : Any , __a : Union[str, Any] , __a : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = TFRegNetModel(config=__a ) __snake_case : Union[str, Any] = model(__a , training=__a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def A_ ( self : List[str] , __a : Dict , __a : Union[str, Any] , __a : Optional[Any] ) -> Tuple: '''simple docstring''' __snake_case : List[str] = self.num_labels __snake_case : List[Any] = TFRegNetForImageClassification(__a ) __snake_case : Optional[int] = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case : Any = config_and_inputs __snake_case : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () A__ = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) A__ = False A__ = False A__ = False A__ = False A__ = False def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' __snake_case : str = TFRegNetModelTester(self ) __snake_case : Optional[Any] = ConfigTester(self , config_class=__a , has_text_modality=__a ) def A_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def A_ ( self : List[str] ) -> Any: '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def A_ ( self : str ) -> str: '''simple docstring''' pass def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Tuple = model_class(__a ) __snake_case : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' def check_hidden_states_output(__a : List[str] , __a : List[Any] , __a : Optional[Any] ): __snake_case : List[Any] = model_class(__a ) __snake_case : int = model(**self._prepare_for_class(__a , __a ) , training=__a ) __snake_case : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : List[Any] = self.model_tester.num_stages self.assertEqual(len(__a ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Optional[int] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: __snake_case : List[str] = layer_type __snake_case : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a ) def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__a : Optional[int] , __a : Tuple , __a : Union[str, Any] , __a : List[Any]={} ): __snake_case : Optional[Any] = model(__a , return_dict=__a , **__a ) __snake_case : Tuple = model(__a , return_dict=__a , **__a ).to_tuple() def recursive_check(__a : Tuple , __a : Optional[int] ): if isinstance(__a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__a , __a ): recursive_check(__a , __a ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__a , __a ) ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(__a , __a ) for model_class in self.all_model_classes: __snake_case : List[str] = model_class(__a ) __snake_case : List[Any] = self._prepare_for_class(__a , __a ) __snake_case : str = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a ) __snake_case : List[str] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Tuple = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) __snake_case : Optional[Any] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Any = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = TFRegNetModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a_ ( ) -> Optional[int]: __snake_case : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def A_ ( self : List[Any] ) -> str: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def A_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __snake_case : str = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : str = image_processor(images=__a , return_tensors='tf' ) # forward pass __snake_case : Optional[int] = model(**__a , training=__a ) # verify the logits __snake_case : List[str] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __snake_case : List[str] = tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , __a , atol=1e-4 )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' import numpy as np def a_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : float = 1E-12 ,_UpperCAmelCase : int = 1_00 ,) -> tuple[float, np.ndarray]: assert np.shape(_UpperCAmelCase )[0] == np.shape(_UpperCAmelCase )[1] # Ensure proper dimensionality. assert np.shape(_UpperCAmelCase )[0] == np.shape(_UpperCAmelCase )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(_UpperCAmelCase ) == np.iscomplexobj(_UpperCAmelCase ) __snake_case : Dict = np.iscomplexobj(_UpperCAmelCase ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(_UpperCAmelCase ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __snake_case : Union[str, Any] = False __snake_case : Dict = 0 __snake_case : Any = 0 __snake_case : List[str] = 1E12 while not convergence: # Multiple matrix by the vector. __snake_case : Union[str, Any] = np.dot(_UpperCAmelCase ,_UpperCAmelCase ) # Normalize the resulting output vector. __snake_case : int = w / np.linalg.norm(_UpperCAmelCase ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __snake_case : Dict = vector.conj().T if is_complex else vector.T __snake_case : Optional[Any] = np.dot(_UpperCAmelCase ,np.dot(_UpperCAmelCase ,_UpperCAmelCase ) ) # Check convergence. __snake_case : Any = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __snake_case : str = True __snake_case : List[Any] = lambda_ if is_complex: __snake_case : List[Any] = np.real(lambda_ ) return lambda_, vector def a_ ( ) -> None: __snake_case : Optional[int] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __snake_case : List[Any] = np.array([41, 4, 20] ) __snake_case : str = real_input_matrix.astype(np.complexaaa ) __snake_case : Optional[int] = np.triu(1J * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __snake_case : int = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __snake_case : List[Any] = real_input_matrix __snake_case : Optional[int] = real_vector elif problem_type == "complex": __snake_case : Dict = complex_input_matrix __snake_case : Dict = complex_vector # Our implementation. __snake_case , __snake_case : Any = power_iteration(_UpperCAmelCase ,_UpperCAmelCase ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __snake_case , __snake_case : List[Any] = np.linalg.eigh(_UpperCAmelCase ) # Last eigenvalue is the maximum one. __snake_case : str = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __snake_case : str = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(_UpperCAmelCase ) - np.abs(_UpperCAmelCase ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import fire from utils import calculate_rouge, save_json def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : str=None ,**_UpperCAmelCase : str ) -> str: __snake_case : List[str] = [x.strip() for x in open(_UpperCAmelCase ).readlines()] __snake_case : List[str] = [x.strip() for x in open(_UpperCAmelCase ).readlines()][: len(_UpperCAmelCase )] __snake_case : List[Any] = calculate_rouge(_UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) if save_path is not None: save_json(_UpperCAmelCase ,_UpperCAmelCase ,indent=_UpperCAmelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: return int((input_a, input_a).count(0 ) != 0 ) def a_ ( ) -> None: assert nand_gate(0 ,0 ) == 1 assert nand_gate(0 ,1 ) == 1 assert nand_gate(1 ,0 ) == 1 assert nand_gate(1 ,1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
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, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = 42 class snake_case__ ( nn.Module ): A__ = 42 A__ = (16, 32, 96, 256) A__ = jnp.floataa def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __snake_case : Tuple = [] for i in range(len(self.block_out_channels ) - 1 ): __snake_case : str = self.block_out_channels[i] __snake_case : Any = self.block_out_channels[i + 1] __snake_case : Optional[int] = nn.Conv( __a , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__a ) __snake_case : Optional[int] = nn.Conv( __a , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__a ) __snake_case : List[Any] = blocks __snake_case : List[str] = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Any , __a : int ) -> List[str]: '''simple docstring''' __snake_case : int = self.conv_in(__a ) __snake_case : Dict = nn.silu(__a ) for block in self.blocks: __snake_case : List[Any] = block(__a ) __snake_case : str = nn.silu(__a ) __snake_case : List[str] = self.conv_out(__a ) return embedding @flax_register_to_config class snake_case__ ( nn.Module , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = 32 A__ = 4 A__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) A__ = False A__ = (320, 640, 1_280, 1_280) A__ = 2 A__ = 8 A__ = None A__ = 1_280 A__ = 0.0 A__ = False A__ = jnp.floataa A__ = True A__ = 0 A__ = "rgb" A__ = (16, 32, 96, 256) def A_ ( self : Optional[Any] , __a : jax.random.KeyArray ) -> FrozenDict: '''simple docstring''' # init input tensors __snake_case : Dict = (1, self.in_channels, self.sample_size, self.sample_size) __snake_case : Union[str, Any] = jnp.zeros(__a , dtype=jnp.floataa ) __snake_case : Optional[int] = jnp.ones((1,) , dtype=jnp.intaa ) __snake_case : List[str] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __snake_case : Any = (1, 3, self.sample_size * 8, self.sample_size * 8) __snake_case : int = jnp.zeros(__a , dtype=jnp.floataa ) __snake_case , __snake_case : Optional[Any] = jax.random.split(__a ) __snake_case : Dict = {'params': params_rng, 'dropout': dropout_rng} return self.init(__a , __a , __a , __a , __a )["params"] def A_ ( self : Tuple ) -> str: '''simple docstring''' __snake_case : str = self.block_out_channels __snake_case : List[Any] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __snake_case : int = self.num_attention_heads or self.attention_head_dim # input __snake_case : int = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __snake_case : Optional[Any] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __snake_case : Union[str, Any] = FlaxTimestepEmbedding(__a , dtype=self.dtype ) __snake_case : Any = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) __snake_case : int = self.only_cross_attention if isinstance(__a , __a ): __snake_case : Optional[Any] = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__a , __a ): __snake_case : Any = (num_attention_heads,) * len(self.down_block_types ) # down __snake_case : List[str] = [] __snake_case : Tuple = [] __snake_case : Tuple = block_out_channels[0] __snake_case : Dict = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a ) for i, down_block_type in enumerate(self.down_block_types ): __snake_case : int = output_channel __snake_case : Union[str, Any] = block_out_channels[i] __snake_case : str = i == len(__a ) - 1 if down_block_type == "CrossAttnDownBlock2D": __snake_case : Union[str, Any] = FlaxCrossAttnDownBlockaD( in_channels=__a , out_channels=__a , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: __snake_case : Tuple = FlaxDownBlockaD( in_channels=__a , out_channels=__a , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__a ) for _ in range(self.layers_per_block ): __snake_case : Tuple = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a ) if not is_final_block: __snake_case : int = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a ) __snake_case : Union[str, Any] = down_blocks __snake_case : Any = controlnet_down_blocks # mid __snake_case : Optional[int] = block_out_channels[-1] __snake_case : List[str] = FlaxUNetMidBlockaDCrossAttn( in_channels=__a , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) __snake_case : List[Any] = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : str , __a : Tuple , __a : Any , __a : Optional[Any] , __a : List[Any] , __a : float = 1.0 , __a : bool = True , __a : bool = False , ) -> Union[FlaxControlNetOutput, Tuple]: '''simple docstring''' __snake_case : int = self.controlnet_conditioning_channel_order if channel_order == "bgr": __snake_case : Tuple = jnp.flip(__a , axis=1 ) # 1. time if not isinstance(__a , jnp.ndarray ): __snake_case : List[str] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__a , jnp.ndarray ) and len(timesteps.shape ) == 0: __snake_case : Any = timesteps.astype(dtype=jnp.floataa ) __snake_case : List[Any] = jnp.expand_dims(__a , 0 ) __snake_case : Dict = self.time_proj(__a ) __snake_case : List[Any] = self.time_embedding(__a ) # 2. pre-process __snake_case : Dict = jnp.transpose(__a , (0, 2, 3, 1) ) __snake_case : Union[str, Any] = self.conv_in(__a ) __snake_case : str = jnp.transpose(__a , (0, 2, 3, 1) ) __snake_case : List[str] = self.controlnet_cond_embedding(__a ) sample += controlnet_cond # 3. down __snake_case : Union[str, Any] = (sample,) for down_block in self.down_blocks: if isinstance(__a , __a ): __snake_case , __snake_case : Union[str, Any] = down_block(__a , __a , __a , deterministic=not train ) else: __snake_case , __snake_case : Tuple = down_block(__a , __a , deterministic=not train ) down_block_res_samples += res_samples # 4. mid __snake_case : List[str] = self.mid_block(__a , __a , __a , deterministic=not train ) # 5. contronet blocks __snake_case : Optional[Any] = () for down_block_res_sample, controlnet_block in zip(__a , self.controlnet_down_blocks ): __snake_case : str = controlnet_block(__a ) controlnet_down_block_res_samples += (down_block_res_sample,) __snake_case : Any = controlnet_down_block_res_samples __snake_case : Any = self.controlnet_mid_block(__a ) # 6. scaling __snake_case : Union[str, Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=__a , mid_block_res_sample=__a )
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __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 ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig A__ : Tuple = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''tapas''' def __init__( self : Optional[int] , __a : List[Any]=30522 , __a : int=768 , __a : int=12 , __a : Tuple=12 , __a : List[Any]=3072 , __a : str="gelu" , __a : Union[str, Any]=0.1 , __a : Union[str, Any]=0.1 , __a : Union[str, Any]=1024 , __a : int=[3, 256, 256, 2, 256, 256, 10] , __a : Dict=0.0_2 , __a : int=1e-12 , __a : str=0 , __a : Dict=1_0.0 , __a : Tuple=0 , __a : Dict=1.0 , __a : str=None , __a : List[Any]=1.0 , __a : Union[str, Any]=False , __a : Any=None , __a : Optional[Any]=1.0 , __a : Dict=1.0 , __a : Dict=False , __a : List[str]=False , __a : List[Any]="ratio" , __a : Tuple=None , __a : str=None , __a : Dict=64 , __a : str=32 , __a : List[Any]=False , __a : int=True , __a : List[str]=False , __a : Any=False , __a : Dict=True , __a : Dict=False , __a : int=None , __a : Optional[int]=None , **__a : List[Any] , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __snake_case : Optional[int] = vocab_size __snake_case : str = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Union[str, Any] = num_attention_heads __snake_case : Any = hidden_act __snake_case : str = intermediate_size __snake_case : Tuple = hidden_dropout_prob __snake_case : List[str] = attention_probs_dropout_prob __snake_case : Dict = max_position_embeddings __snake_case : List[str] = type_vocab_sizes __snake_case : str = initializer_range __snake_case : Tuple = layer_norm_eps # Fine-tuning task hyperparameters __snake_case : Optional[Any] = positive_label_weight __snake_case : Dict = num_aggregation_labels __snake_case : Optional[int] = aggregation_loss_weight __snake_case : List[str] = use_answer_as_supervision __snake_case : int = answer_loss_importance __snake_case : List[Any] = use_normalized_answer_loss __snake_case : Tuple = huber_loss_delta __snake_case : Union[str, Any] = temperature __snake_case : Optional[Any] = aggregation_temperature __snake_case : Tuple = use_gumbel_for_cells __snake_case : List[str] = use_gumbel_for_aggregation __snake_case : str = average_approximation_function __snake_case : Optional[int] = cell_selection_preference __snake_case : Union[str, Any] = answer_loss_cutoff __snake_case : Dict = max_num_rows __snake_case : int = max_num_columns __snake_case : Optional[Any] = average_logits_per_cell __snake_case : Any = select_one_column __snake_case : Any = allow_empty_column_selection __snake_case : str = init_cell_selection_weights_to_zero __snake_case : Union[str, Any] = reset_position_index_per_cell __snake_case : Optional[Any] = disable_per_token_loss # Aggregation hyperparameters __snake_case : Any = aggregation_labels __snake_case : int = no_aggregation_label_index if isinstance(self.aggregation_labels , __a ): __snake_case : int = {int(__a ): v for k, v in aggregation_labels.items()}
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: if num < 0: return False __snake_case : int = num __snake_case : int = 0 while num > 0: __snake_case : str = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
1
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A__ : Optional[int] = logging.get_logger(__name__) A__ : Any = {'''vocab_file''': '''spiece.model'''} A__ : str = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } A__ : Tuple = { '''AI-Sweden/gpt-sw3-126m''': 2_0_4_8, '''AI-Sweden/gpt-sw3-350m''': 2_0_4_8, '''AI-Sweden/gpt-sw3-1.6b''': 2_0_4_8, '''AI-Sweden/gpt-sw3-6.7b''': 2_0_4_8, '''AI-Sweden/gpt-sw3-20b''': 2_0_4_8, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict , __a : int , __a : List[str]=False , __a : int=False , __a : Union[str, Any]=False , __a : Union[str, Any]=None , __a : str=None , __a : Tuple=None , __a : Dict=None , __a : Optional[Dict[str, Any]] = None , **__a : Union[str, Any] , ) -> None: '''simple docstring''' __snake_case : int = {} if sp_model_kwargs is None else sp_model_kwargs __snake_case : Dict = kwargs.get('name_or_path' ) if name_or_path is None: logger.warning( 'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,' ' you are testing the model, this can safely be ignored' ) __snake_case : Tuple = 'None' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __snake_case : str = '<|endoftext|>' if eos_token is None else eos_token __snake_case : Any = '<unk>' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __snake_case : Tuple = unk_token if pad_token is None else pad_token __snake_case : Union[str, Any] = eos_token if bos_token is None else bos_token else: __snake_case : List[str] = '<pad>' if pad_token is None else pad_token __snake_case : List[Any] = '<s>' if bos_token is None else bos_token super().__init__( do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __snake_case : Tuple = do_lower_case __snake_case : Union[str, Any] = remove_space __snake_case : List[Any] = keep_accents __snake_case : Optional[Any] = vocab_file __snake_case : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__a ) # Used for whitespace normalization in input texts # fmt : off __snake_case : Union[str, Any] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '„'} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __snake_case : List[Any] = re.compile( f'''[{"".join(map(__a , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Dict ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[Any] = self.__dict__.copy() __snake_case : List[Any] = None return state def __setstate__( self : Dict , __a : List[Any] ) -> Any: '''simple docstring''' __snake_case : List[Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __snake_case : str = {} __snake_case : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def A_ ( self : int ) -> int: '''simple docstring''' return len(self.sp_model ) def A_ ( self : List[Any] , __a : str ) -> str: '''simple docstring''' __snake_case : Optional[Any] = self.non_printing_characters_re.sub('' , __a ) # Normalize whitespaces __snake_case : Optional[int] = ''.join([char if char not in self.whitespaces else ' ' for char in text] ) # NFC Unicode normalization __snake_case : Any = unicodedata.normalize('NFC' , __a ) return text def A_ ( self : Dict , __a : str , **__a : Dict ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = self.preprocess_text(__a ) return self.sp_model.encode(__a , out_type=__a ) def A_ ( self : List[str] , __a : str ) -> int: '''simple docstring''' return self.sp_model.PieceToId(__a ) def A_ ( self : List[str] , __a : int ) -> str: '''simple docstring''' return self.sp_model.IdToPiece(__a ) @staticmethod def A_ ( __a : str ) -> str: '''simple docstring''' return out_string def A_ ( self : str , __a : List[str] ) -> str: '''simple docstring''' __snake_case : List[str] = [] __snake_case : Optional[Any] = '' __snake_case : Any = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__a ) + token __snake_case : Tuple = True __snake_case : List[str] = [] else: current_sub_tokens.append(__a ) __snake_case : Optional[int] = False out_string += self.sp_model.decode(__a ) return out_string def A_ ( self : List[Any] ) -> Dict[str, int]: '''simple docstring''' __snake_case : Optional[int] = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : str , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __snake_case : int = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , 'wb' ) as fi: __snake_case : List[Any] = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,) def A_ ( self : str , __a : Union[str, List[str]] , __a : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: '''simple docstring''' if isinstance(__a , __a ): __snake_case : Dict = self.preprocess_text(__a ) __snake_case : Tuple = self.sp_model.encode(__a ) else: __snake_case : Tuple = [self.preprocess_text(__a ) for t in text] __snake_case : Optional[Any] = self.sp_model.encode(__a ) if return_tensors is True or return_tensors == "pt": __snake_case : Any = torch.tensor(__a ) return token_ids def A_ ( self : List[Any] , __a : Union[int, List[int]] ) -> str: '''simple docstring''' return self.sp_model.decode(__a ) def A_ ( self : Optional[int] , __a : "Conversation" ) -> List[int]: '''simple docstring''' __snake_case : Any = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __snake_case : Optional[int] = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__a ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__a )
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' class snake_case__ : def __init__( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = {} def A_ ( self : Optional[int] ) -> None: '''simple docstring''' print(self.vertex ) for i in self.vertex: print(__a , ' -> ' , ' -> '.join([str(__a ) for j in self.vertex[i]] ) ) def A_ ( self : Tuple , __a : int , __a : int ) -> None: '''simple docstring''' # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(__a ) else: # else make a new vertex __snake_case : str = [to_vertex] def A_ ( self : List[str] ) -> None: '''simple docstring''' # visited array for storing already visited nodes __snake_case : Dict = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__a , __a ) def A_ ( self : str , __a : int , __a : list ) -> None: '''simple docstring''' # mark start vertex as visited __snake_case : Optional[Any] = True print(__a , end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__a , __a ) if __name__ == "__main__": A__ : Union[str, Any] = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('''DFS:''') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor A__ : Optional[Any] = logging.get_logger(__name__) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , *__a : Optional[Any] , **__a : List[str] ) -> None: '''simple docstring''' warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , __a , ) super().__init__(*__a , **__a )
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer A__ : Dict = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast A__ : Optional[Any] = TaTokenizerFast A__ : Tuple = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[str] = [ '''MT5EncoderModel''', '''MT5ForConditionalGeneration''', '''MT5ForQuestionAnswering''', '''MT5Model''', '''MT5PreTrainedModel''', '''MT5Stack''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model'''] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys A__ : Tuple = _LazyModule( __name__, globals()['''__file__'''], _import_structure, extra_objects={'''MT5Tokenizer''': MTaTokenizer, '''MT5TokenizerFast''': MTaTokenizerFast}, module_spec=__spec__, )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
1
'''simple docstring''' import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def a_ ( *_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Union[Dict, Any]] = None ,_UpperCAmelCase : str=True ,_UpperCAmelCase : str=2 ) -> Optional[int]: from .. import __version__ __snake_case : Union[str, Any] = take_from __snake_case : List[str] = () if not isinstance(args[0] ,_UpperCAmelCase ): __snake_case : List[str] = (args,) for attribute, version_name, message in args: if version.parse(version.parse(_UpperCAmelCase ).base_version ) >= version.parse(_UpperCAmelCase ): raise ValueError( f'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' f''' version {__version__} is >= {version_name}''' ) __snake_case : str = None if isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(_UpperCAmelCase ),) __snake_case : str = f'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(_UpperCAmelCase ,_UpperCAmelCase ): values += (getattr(_UpperCAmelCase ,_UpperCAmelCase ),) __snake_case : Optional[int] = f'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: __snake_case : Optional[Any] = f'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: __snake_case : List[str] = warning + ' ' if standard_warn else '' warnings.warn(warning + message ,_UpperCAmelCase ,stacklevel=_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and len(_UpperCAmelCase ) > 0: __snake_case : Optional[int] = inspect.getouterframes(inspect.currentframe() )[1] __snake_case : Union[str, Any] = call_frame.filename __snake_case : Any = call_frame.lineno __snake_case : Tuple = call_frame.function __snake_case , __snake_case : Any = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(_UpperCAmelCase ) == 0: return elif len(_UpperCAmelCase ) == 1: return values[0] return values
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
1
'''simple docstring''' import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class snake_case__ : def __init__( self : List[str] , __a : Optional[int] , __a : int=14 , __a : Dict=7 , __a : Any=True , __a : str=True , __a : Union[str, Any]=True , __a : Optional[Any]=True , __a : Tuple=True , __a : int=99 , __a : int=32 , __a : List[str]=5 , __a : int=4 , __a : Optional[Any]=37 , __a : Any="gelu" , __a : Optional[int]=0.1 , __a : str=0.1 , __a : Tuple=512 , __a : Tuple=16 , __a : List[str]=2 , __a : Optional[int]=0.0_2 , __a : Tuple=3 , __a : Union[str, Any]=4 , __a : Dict=None , ) -> Tuple: '''simple docstring''' __snake_case : int = parent __snake_case : str = batch_size __snake_case : List[Any] = seq_length __snake_case : Dict = is_training __snake_case : Optional[Any] = use_token_type_ids __snake_case : Optional[int] = use_input_mask __snake_case : Optional[int] = use_labels __snake_case : Dict = use_mc_token_ids __snake_case : List[Any] = vocab_size __snake_case : List[str] = hidden_size __snake_case : List[str] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : Any = intermediate_size __snake_case : Union[str, Any] = hidden_act __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : int = max_position_embeddings __snake_case : str = type_vocab_size __snake_case : List[Any] = type_sequence_label_size __snake_case : Optional[Any] = initializer_range __snake_case : int = num_labels __snake_case : Dict = num_choices __snake_case : int = scope __snake_case : Optional[int] = self.vocab_size - 1 def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Optional[int] = None if self.use_input_mask: __snake_case : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : Any = None if self.use_token_type_ids: __snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : List[Any] = None if self.use_mc_token_ids: __snake_case : Dict = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __snake_case : Optional[Any] = None __snake_case : Tuple = None __snake_case : List[Any] = None if self.use_labels: __snake_case : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __snake_case : int = self.get_config() __snake_case : str = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def A_ ( self : Any , __a : int , __a : Dict , __a : Union[str, Any] , __a : List[Any] , __a : Optional[Any] , *__a : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = CTRLModel(config=__a ) model.to(__a ) model.eval() model(__a , token_type_ids=__a , head_mask=__a ) model(__a , token_type_ids=__a ) __snake_case : Tuple = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def A_ ( self : Any , __a : List[Any] , __a : str , __a : Tuple , __a : Optional[Any] , __a : List[Any] , *__a : List[str] ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[int] = CTRLLMHeadModel(__a ) model.to(__a ) model.eval() __snake_case : List[Any] = model(__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Any = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : List[str] = config_and_inputs __snake_case : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask} return config, inputs_dict def A_ ( self : int , __a : int , __a : Optional[Any] , __a : Optional[Any] , __a : List[str] , *__a : List[Any] ) -> Tuple: '''simple docstring''' __snake_case : int = self.num_labels __snake_case : Union[str, Any] = CTRLForSequenceClassification(__a ) model.to(__a ) model.eval() __snake_case : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Optional[Any] = model(__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () A__ = (CTRLLMHeadModel,) if is_torch_available() else () A__ = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) A__ = True A__ = False A__ = False def A_ ( self : Union[str, Any] , __a : Optional[Any] , __a : List[str] , __a : int , __a : int , __a : List[str] ) -> Union[str, Any]: '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def A_ ( self : Optional[int] ) -> str: '''simple docstring''' __snake_case : List[Any] = CTRLModelTester(self ) __snake_case : Tuple = ConfigTester(self , config_class=__a , n_embd=37 ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : Dict ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*__a ) def A_ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__a ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' pass @slow def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = CTRLModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip('The model doesn\'t support left padding' ) # and it's not used enough to be worth fixing :) def A_ ( self : Any ) -> Any: '''simple docstring''' pass @require_torch class snake_case__ ( unittest.TestCase ): def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Any = CTRLLMHeadModel.from_pretrained('ctrl' ) model.to(__a ) __snake_case : Optional[Any] = torch.tensor( [[11859, 0, 1611, 8]] , dtype=torch.long , device=__a ) # Legal the president is __snake_case : Optional[int] = [ 11859, 0, 1611, 8, 5, 150, 26449, 2, 19, 348, 469, 3, 2595, 48, 20740, 246533, 246533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __snake_case : Any = model.generate(__a , do_sample=__a ) self.assertListEqual(output_ids[0].tolist() , __a )
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __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 A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A__ : str = logging.get_logger(__name__) A__ : List[str] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : Tuple = { '''vocab_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''', }, '''merges_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/tokenizer.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/tokenizer.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/tokenizer.json''', }, } A__ : List[Any] = { '''gpt2''': 1_0_2_4, '''gpt2-medium''': 1_0_2_4, '''gpt2-large''': 1_0_2_4, '''gpt2-xl''': 1_0_2_4, '''distilgpt2''': 1_0_2_4, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['''input_ids''', '''attention_mask'''] A__ = GPTaTokenizer def __init__( self : List[str] , __a : int=None , __a : Union[str, Any]=None , __a : List[str]=None , __a : Union[str, Any]="<|endoftext|>" , __a : Optional[int]="<|endoftext|>" , __a : List[Any]="<|endoftext|>" , __a : Dict=False , **__a : List[str] , ) -> Tuple: '''simple docstring''' super().__init__( __a , __a , tokenizer_file=__a , unk_token=__a , bos_token=__a , eos_token=__a , add_prefix_space=__a , **__a , ) __snake_case : int = kwargs.pop('add_bos_token' , __a ) __snake_case : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __a ) != add_prefix_space: __snake_case : Union[str, Any] = getattr(__a , pre_tok_state.pop('type' ) ) __snake_case : Optional[int] = add_prefix_space __snake_case : int = pre_tok_class(**__a ) __snake_case : int = add_prefix_space def A_ ( self : Dict , *__a : Dict , **__a : int ) -> BatchEncoding: '''simple docstring''' __snake_case : List[Any] = kwargs.get('is_split_into_words' , __a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__a , **__a ) def A_ ( self : List[Any] , *__a : str , **__a : Optional[int] ) -> BatchEncoding: '''simple docstring''' __snake_case : List[str] = kwargs.get('is_split_into_words' , __a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__a , **__a ) def A_ ( self : Dict , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Dict = self._tokenizer.model.save(__a , name=__a ) return tuple(__a ) def A_ ( self : Dict , __a : "Conversation" ) -> List[int]: '''simple docstring''' __snake_case : Optional[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] ) if len(__a ) > self.model_max_length: __snake_case : Tuple = input_ids[-self.model_max_length :] return input_ids
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : int = logging.get_logger(__name__) A__ : int = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''timesformer''' def __init__( self : List[str] , __a : List[Any]=224 , __a : Union[str, Any]=16 , __a : str=3 , __a : int=8 , __a : List[Any]=768 , __a : Dict=12 , __a : Optional[int]=12 , __a : Optional[int]=3072 , __a : Dict="gelu" , __a : Any=0.0 , __a : List[str]=0.0 , __a : Union[str, Any]=0.0_2 , __a : Tuple=1e-6 , __a : Union[str, Any]=True , __a : Optional[Any]="divided_space_time" , __a : Any=0 , **__a : int , ) -> int: '''simple docstring''' super().__init__(**__a ) __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = patch_size __snake_case : int = num_channels __snake_case : int = num_frames __snake_case : Any = hidden_size __snake_case : Union[str, Any] = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Dict = intermediate_size __snake_case : Optional[Any] = hidden_act __snake_case : Union[str, Any] = hidden_dropout_prob __snake_case : List[str] = attention_probs_dropout_prob __snake_case : int = initializer_range __snake_case : Any = layer_norm_eps __snake_case : Optional[int] = qkv_bias __snake_case : Optional[int] = attention_type __snake_case : Optional[int] = drop_path_rate
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py A__ : Optional[Any] = '''.''' if __name__ == "__main__": A__ : Optional[Any] = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') A__ : int = [] A__ : str = [] with open(doctest_file_path) as fp: for line in fp: A__ : Union[str, Any] = line.strip() A__ : Optional[Any] = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: A__ : Union[str, Any] = '''\n'''.join(non_existent_paths) raise ValueError(F"""`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}""") if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A__ : Optional[int] = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[str]=False ) -> Dict: __snake_case : Dict = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('head' ): __snake_case : Any = 'segformer.encoder.' + key if key.startswith('backbone' ): __snake_case : List[Any] = key.replace('backbone' ,'segformer.encoder' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 __snake_case : Union[str, Any] = key[key.find('patch_embed' ) + len('patch_embed' )] __snake_case : Optional[int] = key.replace(f'''patch_embed{idx}''' ,f'''patch_embeddings.{int(_UpperCAmelCase )-1}''' ) if "norm" in key: __snake_case : List[str] = key.replace('norm' ,'layer_norm' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 __snake_case : Tuple = key[key.find('segformer.encoder.layer_norm' ) + len('segformer.encoder.layer_norm' )] __snake_case : Union[str, Any] = key.replace(f'''layer_norm{idx}''' ,f'''layer_norm.{int(_UpperCAmelCase )-1}''' ) if "layer_norm1" in key: __snake_case : str = key.replace('layer_norm1' ,'layer_norm_1' ) if "layer_norm2" in key: __snake_case : int = key.replace('layer_norm2' ,'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 __snake_case : Dict = key[key.find('block' ) + len('block' )] __snake_case : List[str] = key.replace(f'''block{idx}''' ,f'''block.{int(_UpperCAmelCase )-1}''' ) if "attn.q" in key: __snake_case : Dict = key.replace('attn.q' ,'attention.self.query' ) if "attn.proj" in key: __snake_case : List[str] = key.replace('attn.proj' ,'attention.output.dense' ) if "attn" in key: __snake_case : int = key.replace('attn' ,'attention.self' ) if "fc1" in key: __snake_case : Optional[Any] = key.replace('fc1' ,'dense1' ) if "fc2" in key: __snake_case : int = key.replace('fc2' ,'dense2' ) if "linear_pred" in key: __snake_case : Optional[Any] = key.replace('linear_pred' ,'classifier' ) if "linear_fuse" in key: __snake_case : Any = key.replace('linear_fuse.conv' ,'linear_fuse' ) __snake_case : List[str] = key.replace('linear_fuse.bn' ,'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 __snake_case : int = key[key.find('linear_c' ) + len('linear_c' )] __snake_case : List[str] = key.replace(f'''linear_c{idx}''' ,f'''linear_c.{int(_UpperCAmelCase )-1}''' ) if key.startswith('head' ): __snake_case : Any = key.replace('head' ,'classifier' ) __snake_case : List[str] = value return new_state_dict def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[str] ) -> List[Any]: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) __snake_case : List[Any] = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''' ) __snake_case : int = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict __snake_case : int = kv_weight[ : config.hidden_sizes[i], : ] __snake_case : List[str] = kv_bias[: config.hidden_sizes[i]] __snake_case : Union[str, Any] = kv_weight[ config.hidden_sizes[i] :, : ] __snake_case : Optional[Any] = kv_bias[ config.hidden_sizes[i] : ] def a_ ( ) -> str: __snake_case : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __snake_case : Optional[int] = Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ) return image @torch.no_grad() def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: __snake_case : List[Any] = SegformerConfig() __snake_case : Optional[Any] = False # set attributes based on model_name __snake_case : int = 'huggingface/label-files' if "segformer" in model_name: __snake_case : Tuple = model_name[len('segformer.' ) : len('segformer.' ) + 2] if "ade" in model_name: __snake_case : Optional[Any] = 1_50 __snake_case : Optional[int] = 'ade20k-id2label.json' __snake_case : Optional[Any] = (1, 1_50, 1_28, 1_28) elif "city" in model_name: __snake_case : Any = 19 __snake_case : List[Any] = 'cityscapes-id2label.json' __snake_case : Tuple = (1, 19, 1_28, 1_28) else: raise ValueError(f'''Model {model_name} not supported''' ) elif "mit" in model_name: __snake_case : Union[str, Any] = True __snake_case : int = model_name[4:6] __snake_case : Union[str, Any] = 10_00 __snake_case : str = 'imagenet-1k-id2label.json' __snake_case : Any = (1, 10_00) else: raise ValueError(f'''Model {model_name} not supported''' ) # set config attributes __snake_case : List[Any] = json.load(open(hf_hub_download(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ,'r' ) ) __snake_case : Optional[int] = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Dict = idalabel __snake_case : List[Any] = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": __snake_case : List[Any] = [64, 1_28, 3_20, 5_12] __snake_case : str = 2_56 elif size == "b2": __snake_case : int = [64, 1_28, 3_20, 5_12] __snake_case : str = 7_68 __snake_case : Optional[int] = [3, 4, 6, 3] elif size == "b3": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : int = 7_68 __snake_case : Tuple = [3, 4, 18, 3] elif size == "b4": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : Union[str, Any] = 7_68 __snake_case : Union[str, Any] = [3, 8, 27, 3] elif size == "b5": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : int = 7_68 __snake_case : List[str] = [3, 6, 40, 3] else: raise ValueError(f'''Size {size} not supported''' ) # load image processor (only resize + normalize) __snake_case : Optional[Any] = SegformerImageProcessor( image_scale=(5_12, 5_12) ,keep_ratio=_UpperCAmelCase ,align=_UpperCAmelCase ,do_random_crop=_UpperCAmelCase ) # prepare image __snake_case : Dict = prepare_img() __snake_case : List[str] = image_processor(images=_UpperCAmelCase ,return_tensors='pt' ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict if encoder_only: __snake_case : List[Any] = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) else: __snake_case : Optional[Any] = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) )['state_dict'] # rename keys __snake_case : Optional[int] = rename_keys(_UpperCAmelCase ,encoder_only=_UpperCAmelCase ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(_UpperCAmelCase ,_UpperCAmelCase ) # create HuggingFace model and load state dict if encoder_only: __snake_case : Dict = False __snake_case : Union[str, Any] = SegformerForImageClassification(_UpperCAmelCase ) else: __snake_case : Dict = SegformerForSemanticSegmentation(_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() # forward pass __snake_case : List[str] = model(_UpperCAmelCase ) __snake_case : Tuple = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": __snake_case : Tuple = torch.tensor( [ [[-4.6_3_1_0, -5.5_2_3_2, -6.2_3_5_6], [-5.1_9_2_1, -6.1_4_4_4, -6.5_9_9_6], [-5.4_4_2_4, -6.2_7_9_0, -6.7_5_7_4]], [[-1_2.1_3_9_1, -1_3.3_1_2_2, -1_3.9_5_5_4], [-1_2.8_7_3_2, -1_3.9_3_5_2, -1_4.3_5_6_3], [-1_2.9_4_3_8, -1_3.8_2_2_6, -1_4.2_5_1_3]], [[-1_2.5_1_3_4, -1_3.4_6_8_6, -1_4.4_9_1_5], [-1_2.8_6_6_9, -1_4.4_3_4_3, -1_4.7_7_5_8], [-1_3.2_5_2_3, -1_4.5_8_1_9, -1_5.0_6_9_4]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": __snake_case : str = torch.tensor( [ [[-7.5_8_2_0, -8.7_2_3_1, -8.3_2_1_5], [-8.0_6_0_0, -1_0.3_5_2_9, -1_0.0_3_0_4], [-7.5_2_0_8, -9.4_1_0_3, -9.6_2_3_9]], [[-1_2.6_9_1_8, -1_3.8_9_9_4, -1_3.7_1_3_7], [-1_3.3_1_9_6, -1_5.7_5_2_3, -1_5.4_7_8_9], [-1_2.9_3_4_3, -1_4.8_7_5_7, -1_4.9_6_8_9]], [[-1_1.1_9_1_1, -1_1.9_4_2_1, -1_1.3_2_4_3], [-1_1.3_3_4_2, -1_3.6_8_3_9, -1_3.3_5_8_1], [-1_0.3_9_0_9, -1_2.1_8_3_2, -1_2.4_8_5_8]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": __snake_case : Optional[Any] = torch.tensor( [ [[-1_1.8_1_7_3, -1_4.3_8_5_0, -1_6.3_1_2_8], [-1_4.5_6_4_8, -1_6.5_8_0_4, -1_8.6_5_6_8], [-1_4.7_2_2_3, -1_5.7_3_8_7, -1_8.4_2_1_8]], [[-1_5.7_2_9_0, -1_7.9_1_7_1, -1_9.4_4_2_3], [-1_8.3_1_0_5, -1_9.9_4_4_8, -2_1.4_6_6_1], [-1_7.9_2_9_6, -1_8.6_4_9_7, -2_0.7_9_1_0]], [[-1_5.0_7_8_3, -1_7.0_3_3_6, -1_8.2_7_8_9], [-1_6.8_7_7_1, -1_8.6_8_7_0, -2_0.1_6_1_2], [-1_6.2_4_5_4, -1_7.1_4_2_6, -1_9.5_0_5_5]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-9.0_8_7_8, -1_0.2_0_8_1, -1_0.1_8_9_1], [-9.3_1_4_4, -1_0.7_9_4_1, -1_0.9_8_4_3], [-9.2_2_9_4, -1_0.3_8_5_5, -1_0.5_7_0_4]], [[-1_2.2_3_1_6, -1_3.9_0_6_8, -1_3.6_1_0_2], [-1_2.9_1_6_1, -1_4.3_7_0_2, -1_4.3_2_3_5], [-1_2.5_2_3_3, -1_3.7_1_7_4, -1_3.7_9_3_2]], [[-1_4.6_2_7_5, -1_5.2_4_9_0, -1_4.9_7_2_7], [-1_4.3_4_0_0, -1_5.9_6_8_7, -1_6.2_8_2_7], [-1_4.1_4_8_4, -1_5.4_0_3_3, -1_5.8_9_3_7]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": __snake_case : Dict = torch.tensor( [ [[-1_2.3_1_4_4, -1_3.2_4_4_7, -1_4.0_8_0_2], [-1_3.3_6_1_4, -1_4.5_8_1_6, -1_5.6_1_1_7], [-1_3.3_3_4_0, -1_4.4_4_3_3, -1_6.2_2_1_9]], [[-1_9.2_7_8_1, -2_0.4_1_2_8, -2_0.7_5_0_6], [-2_0.6_1_5_3, -2_1.6_5_6_6, -2_2.0_9_9_8], [-1_9.9_8_0_0, -2_1.0_4_3_0, -2_2.1_4_9_4]], [[-1_8.8_7_3_9, -1_9.7_8_0_4, -2_1.1_8_3_4], [-2_0.1_2_3_3, -2_1.6_7_6_5, -2_3.2_9_4_4], [-2_0.0_3_1_5, -2_1.2_6_4_1, -2_3.6_9_4_4]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-9.5_5_2_4, -1_2.0_8_3_5, -1_1.7_3_4_8], [-1_0.5_2_2_9, -1_3.6_4_4_6, -1_4.5_6_6_2], [-9.5_8_4_2, -1_2.8_8_5_1, -1_3.9_4_1_4]], [[-1_5.3_4_3_2, -1_7.5_3_2_3, -1_7.0_8_1_8], [-1_6.3_3_3_0, -1_8.9_2_5_5, -1_9.2_1_0_1], [-1_5.1_3_4_0, -1_7.7_8_4_8, -1_8.3_9_7_1]], [[-1_2.6_0_7_2, -1_4.9_4_8_6, -1_4.6_6_3_1], [-1_3.7_6_2_9, -1_7.0_9_0_7, -1_7.7_7_4_5], [-1_2.7_8_9_9, -1_6.1_6_9_5, -1_7.1_6_7_1]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": __snake_case : List[str] = torch.tensor( [ [[-1_1.9_2_9_5, -1_3.4_0_5_7, -1_4.8_1_0_6], [-1_3.3_4_3_1, -1_4.8_1_7_9, -1_5.3_7_8_1], [-1_4.2_8_3_6, -1_5.5_9_4_2, -1_6.1_5_8_8]], [[-1_1.4_9_0_6, -1_2.8_0_6_7, -1_3.6_5_6_4], [-1_3.1_1_8_9, -1_4.0_5_0_0, -1_4.1_5_4_3], [-1_3.8_7_4_8, -1_4.5_1_3_6, -1_4.8_7_8_9]], [[0.5_3_7_4, 0.1_0_6_7, -0.4_7_4_2], [0.1_1_4_1, -0.2_2_5_5, -0.7_0_9_9], [-0.3_0_0_0, -0.5_9_2_4, -1.3_1_0_5]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": __snake_case : int = torch.tensor( [ [[-7.8_2_1_7, -9.8_7_6_7, -1_0.1_7_1_7], [-9.4_4_3_8, -1_0.9_0_5_8, -1_1.4_0_4_7], [-9.7_9_3_9, -1_2.3_4_9_5, -1_2.1_0_7_9]], [[-7.1_5_1_4, -9.5_3_3_6, -1_0.0_8_6_0], [-9.7_7_7_6, -1_1.6_8_2_2, -1_1.8_4_3_9], [-1_0.1_4_1_1, -1_2.7_6_5_5, -1_2.8_9_7_2]], [[0.3_0_2_1, 0.0_8_0_5, -0.2_3_1_0], [-0.0_3_2_8, -0.1_6_0_5, -0.2_7_1_4], [-0.1_4_0_8, -0.5_4_7_7, -0.6_9_7_6]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": __snake_case : int = torch.tensor( [ [ [-1.1372E01, -1.2787E01, -1.3477E01], [-1.2536E01, -1.4194E01, -1.4409E01], [-1.3217E01, -1.4888E01, -1.5327E01], ], [ [-1.4791E01, -1.7122E01, -1.8277E01], [-1.7163E01, -1.9192E01, -1.9533E01], [-1.7897E01, -1.9991E01, -2.0315E01], ], [ [7.6723E-01, 4.1921E-01, -7.7878E-02], [4.7772E-01, 9.5557E-03, -2.8082E-01], [3.6032E-01, -2.4826E-01, -5.1168E-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": __snake_case : Optional[int] = torch.tensor( [ [[-9.4_9_5_9, -1_1.3_0_8_7, -1_1.7_4_7_9], [-1_1.0_0_2_5, -1_2.6_5_4_0, -1_2.3_3_1_9], [-1_1.4_0_6_4, -1_3.0_4_8_7, -1_2.9_9_0_5]], [[-9.8_9_0_5, -1_1.3_0_8_4, -1_2.0_8_5_4], [-1_1.1_7_2_6, -1_2.7_6_9_8, -1_2.9_5_8_3], [-1_1.5_9_8_5, -1_3.3_2_7_8, -1_4.1_7_7_4]], [[0.2_2_1_3, 0.0_1_9_2, -0.2_4_6_6], [-0.1_7_3_1, -0.4_2_1_3, -0.4_8_7_4], [-0.3_1_2_6, -0.6_5_4_1, -1.1_3_8_9]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": __snake_case : Tuple = torch.tensor( [ [[-1_3.5_7_4_8, -1_3.9_1_1_1, -1_2.6_5_0_0], [-1_4.3_5_0_0, -1_5.3_6_8_3, -1_4.2_3_2_8], [-1_4.7_5_3_2, -1_6.0_4_2_4, -1_5.6_0_8_7]], [[-1_7.1_6_5_1, -1_5.8_7_2_5, -1_2.9_6_5_3], [-1_7.2_5_8_0, -1_7.3_7_1_8, -1_4.8_2_2_3], [-1_6.6_0_5_8, -1_6.8_7_8_3, -1_6.7_4_5_2]], [[-3.6_4_5_6, -3.0_2_0_9, -1.4_2_0_3], [-3.0_7_9_7, -3.1_9_5_9, -2.0_0_0_0], [-1.8_7_5_7, -1.9_2_1_7, -1.6_9_9_7]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": __snake_case : Optional[Any] = torch.tensor( [ [[-1_6.0_9_7_6, -1_6.4_8_5_6, -1_7.3_9_6_2], [-1_6.6_2_3_4, -1_9.0_3_4_2, -1_9.7_6_8_5], [-1_6.0_9_0_0, -1_8.0_6_6_1, -1_9.1_1_8_0]], [[-1_8.4_7_5_0, -1_8.8_4_8_8, -1_9.5_0_7_4], [-1_9.4_0_3_0, -2_2.1_5_7_0, -2_2.5_9_7_7], [-1_9.1_1_9_1, -2_0.8_4_8_6, -2_2.3_7_8_3]], [[-4.5_1_7_8, -5.5_0_3_7, -6.5_1_0_9], [-5.0_8_8_4, -7.2_1_7_4, -8.0_3_3_4], [-4.4_1_5_6, -5.8_1_1_7, -7.2_9_7_0]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-1_4.2_0_8_1, -1_4.4_7_3_2, -1_4.1_9_7_7], [-1_4.5_8_6_7, -1_6.4_4_2_3, -1_6.6_3_5_6], [-1_3.4_4_4_1, -1_4.9_6_8_5, -1_6.8_6_9_6]], [[-1_4.4_5_7_6, -1_4.7_0_7_3, -1_5.0_4_5_1], [-1_5.0_8_1_6, -1_7.6_2_3_7, -1_7.9_8_7_3], [-1_4.4_2_1_3, -1_6.0_1_9_9, -1_8.5_9_9_2]], [[-4.7_3_4_9, -4.9_5_8_8, -5.0_9_6_6], [-4.3_2_1_0, -6.9_3_2_5, -7.2_5_9_1], [-3.4_3_1_2, -4.7_4_8_4, -7.1_9_1_7]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": __snake_case : Optional[int] = torch.tensor( [ [[-1_1.7_7_3_7, -1_1.9_5_2_6, -1_1.3_2_7_3], [-1_3.6_6_9_2, -1_4.4_5_7_4, -1_3.8_8_7_8], [-1_3.8_9_3_7, -1_4.6_9_2_4, -1_5.9_3_4_5]], [[-1_4.6_7_0_6, -1_4.5_3_3_0, -1_4.1_3_0_6], [-1_6.1_5_0_2, -1_6.8_1_8_0, -1_6.4_2_6_9], [-1_6.8_3_3_8, -1_7.8_9_3_9, -2_0.1_7_4_6]], [[1.0_4_9_1, 0.8_2_8_9, 1.0_3_1_0], [1.1_0_4_4, 0.5_2_1_9, 0.8_0_5_5], [1.0_8_9_9, 0.6_9_2_6, 0.5_5_9_0]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": __snake_case : int = torch.tensor( [ [[-1_2.5_6_4_1, -1_3.4_7_7_7, -1_3.0_6_8_4], [-1_3.9_5_8_7, -1_5.8_9_8_3, -1_6.6_5_5_7], [-1_3.3_1_0_9, -1_5.7_3_5_0, -1_6.3_1_4_1]], [[-1_4.7_0_7_4, -1_5.4_3_5_2, -1_4.5_9_4_4], [-1_6.6_3_5_3, -1_8.1_6_6_3, -1_8.6_1_2_0], [-1_5.1_7_0_2, -1_8.0_3_2_9, -1_8.1_5_4_7]], [[-1.7_9_9_0, -2.0_9_5_1, -1.7_7_8_4], [-2.6_3_9_7, -3.8_2_4_5, -3.9_6_8_6], [-1.5_2_6_4, -2.8_1_2_6, -2.9_3_1_6]], ] ) else: __snake_case : Any = logits.argmax(-1 ).item() print('Predicted class:' ,model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] ,_UpperCAmelCase ,atol=1E-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''segformer.b0.512x512.ade.160k''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) A__ : Optional[int] = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
1
'''simple docstring''' import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = (PNDMScheduler,) A__ = (('''num_inference_steps''', 50),) def A_ ( self : Any , **__a : Any ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = { 'num_train_timesteps': 1000, 'beta_start': 0.0_0_0_1, 'beta_end': 0.0_2, 'beta_schedule': 'linear', } config.update(**__a ) return config def A_ ( self : List[str] , __a : Dict=0 , **__a : str ) -> List[str]: '''simple docstring''' __snake_case : Dict = dict(self.forward_default_kwargs ) __snake_case : List[Any] = kwargs.pop('num_inference_steps' , __a ) __snake_case : Dict = self.dummy_sample __snake_case : Any = 0.1 * sample __snake_case : str = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: __snake_case : str = self.get_scheduler_config(**__a ) __snake_case : List[str] = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals __snake_case : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) __snake_case : Optional[int] = scheduler_class.from_pretrained(__a ) new_scheduler.set_timesteps(__a ) # copy over dummy past residuals __snake_case : Optional[int] = dummy_past_residuals[:] __snake_case : Optional[int] = scheduler.step_prk(__a , __a , __a , **__a ).prev_sample __snake_case : Optional[Any] = new_scheduler.step_prk(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __snake_case : Dict = scheduler.step_plms(__a , __a , __a , **__a ).prev_sample __snake_case : Dict = new_scheduler.step_plms(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' pass def A_ ( self : Any , __a : int=0 , **__a : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Any = dict(self.forward_default_kwargs ) __snake_case : Any = kwargs.pop('num_inference_steps' , __a ) __snake_case : Union[str, Any] = self.dummy_sample __snake_case : Union[str, Any] = 0.1 * sample __snake_case : Any = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: __snake_case : Optional[Any] = self.get_scheduler_config() __snake_case : int = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals (must be after setting timesteps) __snake_case : Tuple = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) __snake_case : int = scheduler_class.from_pretrained(__a ) # copy over dummy past residuals new_scheduler.set_timesteps(__a ) # copy over dummy past residual (must be after setting timesteps) __snake_case : str = dummy_past_residuals[:] __snake_case : Dict = scheduler.step_prk(__a , __a , __a , **__a ).prev_sample __snake_case : List[str] = new_scheduler.step_prk(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __snake_case : List[Any] = scheduler.step_plms(__a , __a , __a , **__a ).prev_sample __snake_case : List[str] = new_scheduler.step_plms(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def A_ ( self : Tuple , **__a : int ) -> Dict: '''simple docstring''' __snake_case : List[Any] = self.scheduler_classes[0] __snake_case : Tuple = self.get_scheduler_config(**__a ) __snake_case : Any = scheduler_class(**__a ) __snake_case : int = 10 __snake_case : List[str] = self.dummy_model() __snake_case : Any = self.dummy_sample_deter scheduler.set_timesteps(__a ) for i, t in enumerate(scheduler.prk_timesteps ): __snake_case : List[str] = model(__a , __a ) __snake_case : Optional[Any] = scheduler.step_prk(__a , __a , __a ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): __snake_case : Dict = model(__a , __a ) __snake_case : List[Any] = scheduler.step_plms(__a , __a , __a ).prev_sample return sample def A_ ( self : int ) -> str: '''simple docstring''' __snake_case : int = dict(self.forward_default_kwargs ) __snake_case : Any = kwargs.pop('num_inference_steps' , __a ) for scheduler_class in self.scheduler_classes: __snake_case : List[Any] = self.get_scheduler_config() __snake_case : Tuple = scheduler_class(**__a ) __snake_case : List[Any] = self.dummy_sample __snake_case : Union[str, Any] = 0.1 * sample if num_inference_steps is not None and hasattr(__a , 'set_timesteps' ): scheduler.set_timesteps(__a ) elif num_inference_steps is not None and not hasattr(__a , 'set_timesteps' ): __snake_case : Dict = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __snake_case : str = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] __snake_case : Optional[Any] = dummy_past_residuals[:] __snake_case : Optional[int] = scheduler.step_prk(__a , 0 , __a , **__a ).prev_sample __snake_case : Union[str, Any] = scheduler.step_prk(__a , 1 , __a , **__a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __snake_case : List[Any] = scheduler.step_plms(__a , 0 , __a , **__a ).prev_sample __snake_case : List[str] = scheduler.step_plms(__a , 1 , __a , **__a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def A_ ( self : str ) -> Optional[Any]: '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__a ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) __snake_case : str = self.scheduler_classes[0] __snake_case : List[Any] = self.get_scheduler_config(steps_offset=1 ) __snake_case : int = scheduler_class(**__a ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def A_ ( self : int ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1] , [0.0_0_2, 0.0_2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def A_ ( self : Dict ) -> Any: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def A_ ( self : Tuple ) -> int: '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=__a ) def A_ ( self : List[str] ) -> Any: '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__a ) def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 __snake_case : Dict = 27 for scheduler_class in self.scheduler_classes: __snake_case : int = self.dummy_sample __snake_case : str = 0.1 * sample __snake_case : Optional[Any] = self.get_scheduler_config() __snake_case : Union[str, Any] = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): __snake_case : int = scheduler.step_prk(__a , __a , __a ).prev_sample def A_ ( self : Tuple ) -> str: '''simple docstring''' with self.assertRaises(__a ): __snake_case : int = self.scheduler_classes[0] __snake_case : int = self.get_scheduler_config() __snake_case : List[Any] = scheduler_class(**__a ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def A_ ( self : Dict ) -> int: '''simple docstring''' __snake_case : Tuple = self.full_loop() __snake_case : int = torch.sum(torch.abs(__a ) ) __snake_case : List[str] = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_9_8.1_3_1_8 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_8_0 ) < 1e-3 def A_ ( self : List[str] ) -> int: '''simple docstring''' __snake_case : List[str] = self.full_loop(prediction_type='v_prediction' ) __snake_case : int = torch.sum(torch.abs(__a ) ) __snake_case : Union[str, Any] = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 6_7.3_9_8_6 ) < 1e-2 assert abs(result_mean.item() - 0.0_8_7_8 ) < 1e-3 def A_ ( self : Dict ) -> str: '''simple docstring''' # We specify different beta, so that the first alpha is 0.99 __snake_case : Any = self.full_loop(set_alpha_to_one=__a , beta_start=0.0_1 ) __snake_case : int = torch.sum(torch.abs(__a ) ) __snake_case : Optional[Any] = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 2_3_0.0_3_9_9 ) < 1e-2 assert abs(result_mean.item() - 0.2_9_9_5 ) < 1e-3 def A_ ( self : int ) -> Tuple: '''simple docstring''' # We specify different beta, so that the first alpha is 0.99 __snake_case : str = self.full_loop(set_alpha_to_one=__a , beta_start=0.0_1 ) __snake_case : List[Any] = torch.sum(torch.abs(__a ) ) __snake_case : Any = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_8_6.9_4_8_2 ) < 1e-2 assert abs(result_mean.item() - 0.2_4_3_4 ) < 1e-3
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. A__ : Optional[int] = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class snake_case__ ( unittest.TestCase ): A__ = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A__ = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: A__ = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: A__ = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def A_ ( self : Union[str, Any] , __a : str , __a : Optional[Any] , __a : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = ZeroShotClassificationPipeline( model=__a , tokenizer=__a , candidate_labels=['polics', 'health'] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def A_ ( self : List[Any] , __a : Union[str, Any] , __a : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = classifier('Who are you voting for in 2020?' , candidate_labels='politics' ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) # No kwarg __snake_case : List[str] = classifier('Who are you voting for in 2020?' , ['politics'] ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) __snake_case : int = classifier('Who are you voting for in 2020?' , candidate_labels=['politics'] ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) __snake_case : Dict = classifier('Who are you voting for in 2020?' , candidate_labels='politics, public health' ) self.assertEqual( __a , {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __snake_case : Optional[Any] = classifier('Who are you voting for in 2020?' , candidate_labels=['politics', 'public health'] ) self.assertEqual( __a , {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __snake_case : Tuple = classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='This text is about {}' ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) # https://github.com/huggingface/transformers/issues/13846 __snake_case : List[Any] = classifier(['I am happy'] , ['positive', 'negative'] ) self.assertEqual( __a , [ {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} for i in range(1 ) ] , ) __snake_case : Union[str, Any] = classifier(['I am happy', 'I am sad'] , ['positive', 'negative'] ) self.assertEqual( __a , [ {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} for i in range(2 ) ] , ) with self.assertRaises(__a ): classifier('' , candidate_labels='politics' ) with self.assertRaises(__a ): classifier(__a , candidate_labels='politics' ) with self.assertRaises(__a ): classifier('Who are you voting for in 2020?' , candidate_labels='' ) with self.assertRaises(__a ): classifier('Who are you voting for in 2020?' , candidate_labels=__a ) with self.assertRaises(__a ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='Not formatting template' , ) with self.assertRaises(__a ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template=__a , ) self.run_entailment_id(__a ) def A_ ( self : int , __a : Pipeline ) -> Dict: '''simple docstring''' __snake_case : List[str] = zero_shot_classifier.model.config __snake_case : Union[str, Any] = config.labelaid __snake_case : int = zero_shot_classifier.entailment_id __snake_case : str = {'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __snake_case : int = {'entailment': 0, 'neutral': 1, 'contradiction': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __snake_case : Optional[Any] = {'ENTAIL': 0, 'NON-ENTAIL': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __snake_case : Optional[int] = {'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __snake_case : str = original_labelaid self.assertEqual(__a , zero_shot_classifier.entailment_id ) @require_torch def A_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : List[str] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( 'Who are you voting for in 2020?' * 100 , candidate_labels=['politics', 'public health', 'science'] ) @require_torch def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : Optional[int] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) __snake_case : str = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @require_tf def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='tf' , ) __snake_case : str = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @slow @require_torch def A_ ( self : List[str] ) -> Any: '''simple docstring''' __snake_case : List[str] = pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='pt' ) __snake_case : List[str] = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) __snake_case : str = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=__a , ) self.assertEqual( nested_simplify(__a ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , ) @slow @require_tf def A_ ( self : str ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='tf' ) __snake_case : Tuple = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) __snake_case : int = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=__a , ) self.assertEqual( nested_simplify(__a ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , )
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Optional[int] = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json''' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''decision_transformer''' A__ = ['''past_key_values'''] A__ = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : str , __a : Union[str, Any]=17 , __a : Dict=4 , __a : str=128 , __a : Tuple=4096 , __a : str=True , __a : List[str]=1 , __a : Optional[Any]=1024 , __a : Any=3 , __a : List[str]=1 , __a : str=None , __a : Union[str, Any]="relu" , __a : Optional[Any]=0.1 , __a : str=0.1 , __a : List[str]=0.1 , __a : Any=1e-5 , __a : Dict=0.0_2 , __a : str=True , __a : str=True , __a : List[str]=50256 , __a : Any=50256 , __a : str=False , __a : List[str]=False , **__a : List[str] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[Any] = state_dim __snake_case : Dict = act_dim __snake_case : Optional[int] = hidden_size __snake_case : int = max_ep_len __snake_case : Tuple = action_tanh __snake_case : str = vocab_size __snake_case : Tuple = n_positions __snake_case : Optional[Any] = n_layer __snake_case : int = n_head __snake_case : List[str] = n_inner __snake_case : List[Any] = activation_function __snake_case : Optional[Any] = resid_pdrop __snake_case : List[str] = embd_pdrop __snake_case : List[Any] = attn_pdrop __snake_case : Any = layer_norm_epsilon __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = scale_attn_weights __snake_case : str = use_cache __snake_case : List[Any] = scale_attn_by_inverse_layer_idx __snake_case : Optional[int] = reorder_and_upcast_attn __snake_case : Dict = bos_token_id __snake_case : Tuple = eos_token_id super().__init__(bos_token_id=__a , eos_token_id=__a , **__a )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : str = "The quick brown fox jumps over the lazy dog" ,) -> bool: __snake_case : Optional[Any] = set() # Replace all the whitespace in our sentence __snake_case : int = input_str.replace(' ' ,'' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(_UpperCAmelCase ) == 26 def a_ ( _UpperCAmelCase : str = "The quick brown fox jumps over the lazy dog" ,) -> bool: __snake_case : int = [False] * 26 for char in input_str: if char.islower(): __snake_case : Optional[int] = True elif char.isupper(): __snake_case : Union[str, Any] = True return all(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str = "The quick brown fox jumps over the lazy dog" ,) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def a_ ( ) -> None: from timeit import timeit __snake_case : Union[str, Any] = 'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' ,setup=_UpperCAmelCase ) ) print(timeit('is_pangram_faster()' ,setup=_UpperCAmelCase ) ) print(timeit('is_pangram_fastest()' ,setup=_UpperCAmelCase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin A__ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''') A__ : Dict = {'''target_lang''': '''fi''', '''source_lang''': '''en'''} A__ : Any = '''>>zh<<''' A__ : List[Any] = '''Helsinki-NLP/''' if is_torch_available(): A__ : Union[str, Any] = '''pt''' elif is_tf_available(): A__ : Union[str, Any] = '''tf''' else: A__ : str = '''jax''' @require_sentencepiece class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = MarianTokenizer A__ = False A__ = True def A_ ( self : Any ) -> Tuple: '''simple docstring''' super().setUp() __snake_case : List[str] = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>'] __snake_case : Any = dict(zip(__a , range(len(__a ) ) ) ) __snake_case : List[str] = Path(self.tmpdirname ) save_json(__a , save_dir / VOCAB_FILES_NAMES['vocab'] ) save_json(__a , save_dir / VOCAB_FILES_NAMES['tokenizer_config_file'] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__a , save_dir / VOCAB_FILES_NAMES['source_spm'] ) copyfile(__a , save_dir / VOCAB_FILES_NAMES['target_spm'] ) __snake_case : Union[str, Any] = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : Any , **__a : int ) -> MarianTokenizer: '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : List[Any] , __a : Dict ) -> Any: '''simple docstring''' return ( "This is a test", "This is a test", ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Optional[int] = '</s>' __snake_case : List[str] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def A_ ( self : List[str] ) -> int: '''simple docstring''' __snake_case : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '</s>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(__a ) , 9 ) def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : str = MarianTokenizer.from_pretrained(f'''{ORG_NAME}opus-mt-en-de''' ) __snake_case : Tuple = en_de_tokenizer(['I am a small frog'] , return_tensors=__a ) self.assertIsInstance(__a , __a ) __snake_case : Tuple = [38, 121, 14, 697, 38848, 0] self.assertListEqual(__a , batch.input_ids[0] ) __snake_case : List[Any] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__a ) __snake_case : Optional[Any] = [x.name for x in Path(__a ).glob('*' )] self.assertIn('source.spm' , __a ) MarianTokenizer.from_pretrained(__a ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = self.get_tokenizer() __snake_case : Dict = tok( ['I am a small frog' * 1000, 'I am a small frog'] , padding=__a , truncation=__a , return_tensors=__a ) self.assertIsInstance(__a , __a ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def A_ ( self : Any ) -> Dict: '''simple docstring''' __snake_case : int = self.get_tokenizer() __snake_case : List[str] = tok(['I am a tiny frog', 'I am a small frog'] , padding=__a , return_tensors=__a ) self.assertIsInstance(__a , __a ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' # fmt: off __snake_case : str = {'input_ids': [[43495, 462, 20, 42164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 38999, 6, 8, 464, 132, 1703, 492, 13, 4669, 37867, 13, 7525, 27, 1593, 988, 13, 33972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 12338, 2, 13958, 387, 2, 3629, 6953, 188, 2900, 2, 13958, 8011, 11501, 23, 8460, 4073, 34009, 20, 435, 11439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 37867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 26453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10767, 6, 316, 304, 4239, 3, 0], [148, 15722, 19, 1839, 12, 1350, 13, 22327, 5082, 5418, 47567, 35938, 59, 318, 19552, 108, 2183, 54, 14976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 19088, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100], [36, 6395, 12570, 39147, 11597, 6, 266, 4, 45405, 7296, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name='Helsinki-NLP/opus-mt-en-de' , revision='1a8c2263da11e68e50938f97e10cd57820bd504c' , decode_kwargs={'use_source_tokenizer': True} , ) def A_ ( self : Tuple ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = MarianTokenizer.from_pretrained('hf-internal-testing/test-marian-two-vocabs' ) __snake_case : List[Any] = 'Tämä on testi' __snake_case : List[str] = 'This is a test' __snake_case : Union[str, Any] = [76, 7, 2047, 2] __snake_case : Tuple = [69, 12, 11, 940, 2] __snake_case : Optional[Any] = tokenizer(__a ).input_ids self.assertListEqual(__a , __a ) __snake_case : str = tokenizer(text_target=__a ).input_ids self.assertListEqual(__a , __a ) __snake_case : Dict = tokenizer.decode(__a , skip_special_tokens=__a ) self.assertEqual(__a , __a )
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { '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, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version A__ : int = logging.getLogger(__name__) require_version('''pytorch_lightning>=1.0.4''') A__ : List[str] = { '''base''': AutoModel, '''sequence-classification''': AutoModelForSequenceClassification, '''question-answering''': AutoModelForQuestionAnswering, '''pretraining''': AutoModelForPreTraining, '''token-classification''': AutoModelForTokenClassification, '''language-modeling''': AutoModelWithLMHead, '''summarization''': AutoModelForSeqaSeqLM, '''translation''': AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization A__ : Any = { '''linear''': get_linear_schedule_with_warmup, '''cosine''': get_cosine_schedule_with_warmup, '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup, '''polynomial''': get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } A__ : List[Any] = sorted(arg_to_scheduler.keys()) A__ : Optional[Any] = '''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}''' class snake_case__ ( pl.LightningModule ): def __init__( self : Tuple , __a : argparse.Namespace , __a : Dict=None , __a : List[str]="base" , __a : int=None , __a : Optional[Any]=None , __a : Dict=None , **__a : Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__a ) __snake_case : Tuple = 0 __snake_case : Optional[Any] = Path(self.hparams.output_dir ) __snake_case : List[Any] = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: __snake_case : Optional[Any] = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'num_labels': num_labels} if num_labels is not None else {}) , cache_dir=__a , **__a , ) else: __snake_case : PretrainedConfig = config __snake_case : Optional[Any] = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(self.hparams , __a , __a ): assert hasattr(self.config , __a ), f'''model config doesn\'t have a `{p}` attribute''' setattr(self.config , __a , getattr(self.hparams , __a ) ) if tokenizer is None: __snake_case : Dict = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__a , ) else: __snake_case : PreTrainedTokenizer = tokenizer __snake_case : Dict = MODEL_MODES[mode] if model is None: __snake_case : Union[str, Any] = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('.ckpt' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__a , ) else: __snake_case : Optional[Any] = model def A_ ( self : int , *__a : int , **__a : Any ) -> int: '''simple docstring''' __snake_case : List[Any] = self.model_type.from_pretrained(*__a , **__a ) def A_ ( self : Tuple ) -> Dict: '''simple docstring''' __snake_case : List[str] = arg_to_scheduler[self.hparams.lr_scheduler] __snake_case : Optional[Any] = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) __snake_case : Tuple = {'scheduler': scheduler, 'interval': 'step', 'frequency': 1} return scheduler def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.model __snake_case : str = ['bias', 'LayerNorm.weight'] __snake_case : Optional[Any] = [ { 'params': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters 'weight_decay': self.hparams.weight_decay, }, { 'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] if self.hparams.adafactor: __snake_case : str = Adafactor( __a , lr=self.hparams.learning_rate , scale_parameter=__a , relative_step=__a ) else: __snake_case : Any = AdamW( __a , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) __snake_case : Dict = optimizer __snake_case : List[Any] = self.get_lr_scheduler() return [optimizer], [scheduler] def A_ ( self : Union[str, Any] , __a : str , __a : Tuple ) -> str: '''simple docstring''' return self.validation_step(__a , __a ) def A_ ( self : List[Any] , __a : Tuple ) -> List[Any]: '''simple docstring''' return self.validation_end(__a ) def A_ ( self : int ) -> int: '''simple docstring''' __snake_case : int = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores __snake_case : List[Any] = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def A_ ( self : Optional[int] , __a : Tuple ) -> int: '''simple docstring''' if stage == "test": __snake_case : Union[str, Any] = len(self.test_dataloader().dataset ) else: __snake_case : Dict = self.get_dataloader('train' , self.hparams.train_batch_size , shuffle=__a ) __snake_case : int = len(self.train_dataloader().dataset ) def A_ ( self : Union[str, Any] , __a : str , __a : int , __a : bool = False ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError('You must implement this for your task' ) def A_ ( self : int ) -> Optional[Any]: '''simple docstring''' return self.train_loader def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.get_dataloader('dev' , self.hparams.eval_batch_size , shuffle=__a ) def A_ ( self : Dict ) -> Dict: '''simple docstring''' return self.get_dataloader('test' , self.hparams.eval_batch_size , shuffle=__a ) def A_ ( self : str , __a : Dict ) -> str: '''simple docstring''' return os.path.join( self.hparams.data_dir , 'cached_{}_{}_{}'.format( __a , list(filter(__a , self.hparams.model_name_or_path.split('/' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def A_ ( self : List[str] , __a : Dict[str, Any] ) -> None: '''simple docstring''' __snake_case : List[Any] = self.output_dir.joinpath('best_tfmr' ) __snake_case : Optional[int] = self.step_count self.model.save_pretrained(__a ) self.tokenizer.save_pretrained(__a ) @staticmethod def A_ ( __a : str , __a : Any ) -> Optional[Any]: '''simple docstring''' parser.add_argument( '--model_name_or_path' , default=__a , type=__a , required=__a , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--config_name' , default='' , type=__a , help='Pretrained config name or path if not the same as model_name' ) parser.add_argument( '--tokenizer_name' , default=__a , type=__a , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument( '--cache_dir' , default=str(Path(__a ).parent / 'test_run' / 'cache' ) , type=__a , help='Where do you want to store the pre-trained models downloaded from huggingface.co' , ) parser.add_argument( '--encoder_layerdrop' , type=__a , help='Encoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--decoder_layerdrop' , type=__a , help='Decoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--dropout' , type=__a , help='Dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--attention_dropout' , type=__a , help='Attention dropout probability (Optional). Goes into model.config' , ) parser.add_argument('--learning_rate' , default=5e-5 , type=__a , help='The initial learning rate for Adam.' ) parser.add_argument( '--lr_scheduler' , default='linear' , choices=__a , metavar=__a , type=__a , help='Learning rate scheduler' , ) parser.add_argument('--weight_decay' , default=0.0 , type=__a , help='Weight decay if we apply some.' ) parser.add_argument('--adam_epsilon' , default=1e-8 , type=__a , help='Epsilon for Adam optimizer.' ) parser.add_argument('--warmup_steps' , default=0 , type=__a , help='Linear warmup over warmup_steps.' ) parser.add_argument('--num_workers' , default=4 , type=__a , help='kwarg passed to DataLoader' ) parser.add_argument('--num_train_epochs' , dest='max_epochs' , default=3 , type=__a ) parser.add_argument('--train_batch_size' , default=32 , type=__a ) parser.add_argument('--eval_batch_size' , default=32 , type=__a ) parser.add_argument('--adafactor' , action='store_true' ) class snake_case__ ( pl.Callback ): def A_ ( self : int , __a : Optional[int] , __a : Optional[Any] ) -> Dict: '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class snake_case__ ( pl.Callback ): def A_ ( self : Tuple , __a : List[str] , __a : Dict ) -> Any: '''simple docstring''' # print(pl_module.model.rag) for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__a ) class snake_case__ ( pl.Callback ): def A_ ( self : int , __a : int , __a : int ) -> str: '''simple docstring''' __snake_case : Optional[int] = trainer.lr_schedulers[0]['scheduler'] __snake_case : Optional[int] = {f'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__a ) def A_ ( self : Optional[int] , __a : pl.Trainer , __a : pl.LightningModule ) -> Union[str, Any]: '''simple docstring''' rank_zero_info('***** Validation results *****' ) __snake_case : Union[str, Any] = trainer.callback_metrics # Log results for key in sorted(__a ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__a , str(metrics[key] ) ) ) def A_ ( self : str , __a : pl.Trainer , __a : pl.LightningModule ) -> Union[str, Any]: '''simple docstring''' rank_zero_info('***** Test results *****' ) __snake_case : Optional[int] = trainer.callback_metrics # Log and save results to file __snake_case : Optional[Any] = os.path.join(pl_module.hparams.output_dir , 'test_results.txt' ) with open(__a , 'w' ) as writer: for key in sorted(__a ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__a , str(metrics[key] ) ) ) writer.write('{} = {}\n'.format(__a , str(metrics[key] ) ) ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ) -> None: # To allow all pl args uncomment the following line # parser = pl.Trainer.add_argparse_args(parser) parser.add_argument( '--output_dir' ,default=str(Path(_UpperCAmelCase ).parent / 'test_run' / 'model_checkpoints' ) ,type=_UpperCAmelCase ,help='The output directory where the model predictions and checkpoints will be written.' ,) parser.add_argument( '--fp16' ,action='store_true' ,help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' ,) parser.add_argument( '--fp16_opt_level' ,type=_UpperCAmelCase ,default='O2' ,help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) ,) parser.add_argument('--n_tpu_cores' ,dest='tpu_cores' ,type=_UpperCAmelCase ) parser.add_argument('--max_grad_norm' ,dest='gradient_clip_val' ,default=1.0 ,type=_UpperCAmelCase ,help='Max gradient norm' ) parser.add_argument('--do_train' ,action='store_true' ,help='Whether to run training.' ) parser.add_argument('--do_predict' ,action='store_true' ,help='Whether to run predictions on the test set.' ) parser.add_argument( '--gradient_accumulation_steps' ,dest='accumulate_grad_batches' ,type=_UpperCAmelCase ,default=1 ,help='Number of updates steps to accumulate before performing a backward/update pass.' ,) parser.add_argument('--seed' ,type=_UpperCAmelCase ,default=42 ,help='random seed for initialization' ) parser.add_argument( '--data_dir' ,default=str(Path(_UpperCAmelCase ).parent / 'test_run' / 'dummy-train-data' ) ,type=_UpperCAmelCase ,help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.' ,) def a_ ( _UpperCAmelCase : BaseTransformer ,_UpperCAmelCase : argparse.Namespace ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=True ,_UpperCAmelCase : Tuple=[] ,_UpperCAmelCase : List[str]=None ,_UpperCAmelCase : Union[str, Any]=None ,**_UpperCAmelCase : List[str] ,) -> Optional[Any]: pl.seed_everything(args.seed ) # init model __snake_case : Optional[Any] = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=_UpperCAmelCase ) # add custom checkpoints if checkpoint_callback is None: __snake_case : Optional[int] = pl.callbacks.ModelCheckpoint( filepath=args.output_dir ,prefix='checkpoint' ,monitor='val_loss' ,mode='min' ,save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(_UpperCAmelCase ) if logging_callback is None: __snake_case : List[Any] = LoggingCallback() __snake_case : List[str] = {} if args.fpaa: __snake_case : str = 16 if args.gpus > 1: __snake_case : List[str] = 'auto' __snake_case : Tuple = 'ddp' __snake_case : Union[str, Any] = args.accumulate_grad_batches __snake_case : List[Any] = None __snake_case : Optional[int] = 'auto' __snake_case : Union[str, Any] = pl.Trainer.from_argparse_args( _UpperCAmelCase ,weights_summary=_UpperCAmelCase ,callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] ,logger=_UpperCAmelCase ,val_check_interval=1 ,num_sanity_val_steps=2 ,**_UpperCAmelCase ,) if args.do_train: trainer.fit(_UpperCAmelCase ) else: print('RAG modeling tests with new set functions successfuly executed!' ) return trainer
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ) -> List[str]: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Tuple = np.full((len(_UpperCAmelCase ), sequence_length, 2) ,_UpperCAmelCase ) else: __snake_case : int = np.full((len(_UpperCAmelCase ), sequence_length) ,_UpperCAmelCase ) for i, tensor in enumerate(_UpperCAmelCase ): if padding_side == "right": if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Dict = tensor[:sequence_length] else: __snake_case : List[Any] = tensor[:sequence_length] else: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : str = tensor[:sequence_length] else: __snake_case : int = tensor[:sequence_length] return out_tensor.tolist() def a_ ( _UpperCAmelCase : Any ) -> Optional[int]: __snake_case : List[Any] = ord(_UpperCAmelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26): return True __snake_case : Dict = unicodedata.category(_UpperCAmelCase ) if cat.startswith('P' ): return True return False @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = True A__ = None A__ = None A__ = -100 A__ = "pt" def A_ ( self : Any , __a : Dict ) -> List[str]: '''simple docstring''' import torch __snake_case : Optional[int] = 'label' if 'label' in features[0].keys() else 'labels' __snake_case : int = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __snake_case : Union[str, Any] = self.tokenizer.pad( __a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' if labels is None else None , ) if labels is None: return batch __snake_case : Union[str, Any] = torch.tensor(batch['entity_ids'] ).shape[1] __snake_case : Union[str, Any] = self.tokenizer.padding_side if padding_side == "right": __snake_case : Tuple = [ list(__a ) + [self.label_pad_token_id] * (sequence_length - len(__a )) for label in labels ] else: __snake_case : str = [ [self.label_pad_token_id] * (sequence_length - len(__a )) + list(__a ) for label in labels ] __snake_case : Optional[Any] = [feature['ner_tags'] for feature in features] __snake_case : List[Any] = padding_tensor(__a , -1 , __a , __a ) __snake_case : List[Any] = [feature['original_entity_spans'] for feature in features] __snake_case : List[str] = padding_tensor(__a , (-1, -1) , __a , __a ) __snake_case : Optional[Any] = {k: torch.tensor(__a , dtype=torch.intaa ) for k, v in batch.items()} return batch
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __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 ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
1
'''simple docstring''' import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = BertJapaneseTokenizer A__ = False A__ = True def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' super().setUp() __snake_case : List[str] = [ '[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは', '世界', '##世界', '、', '##、', '。', '##。', ] __snake_case : str = 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 A_ ( self : List[str] , __a : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = 'こんにちは、世界。 \nこんばんは、世界。' __snake_case : Tuple = 'こんにちは 、 世界 。 こんばんは 、 世界 。' return input_text, output_text def A_ ( self : List[str] , __a : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case , __snake_case : Dict = self.get_input_output_texts(__a ) __snake_case : List[str] = tokenizer.encode(__a , add_special_tokens=__a ) __snake_case : int = tokenizer.decode(__a , clean_up_tokenization_spaces=__a ) return text, ids def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' pass # TODO add if relevant def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def A_ ( self : str ) -> int: '''simple docstring''' pass # TODO add if relevant def A_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class(self.vocab_file ) __snake_case : Tuple = tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。' ) self.assertListEqual(__a , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : int = self.tokenizer_class(self.vocab_file , word_tokenizer_type='mecab' ) self.assertIsNotNone(__a ) __snake_case : Optional[Any] = 'こんにちは、世界。\nこんばんは、世界。' __snake_case : List[str] = tokenizer.tokenize(__a ) self.assertListEqual(__a , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __snake_case : List[Any] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__a , 'wb' ) as handle: pickle.dump(__a , __a ) with open(__a , 'rb' ) as handle: __snake_case : Any = pickle.load(__a ) __snake_case : Dict = tokenizer_new.tokenize(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> str: '''simple docstring''' __snake_case : List[Any] = MecabTokenizer(mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' try: __snake_case : int = MecabTokenizer(mecab_dic='unidic_lite' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def A_ ( self : List[Any] ) -> str: '''simple docstring''' try: __snake_case : Dict = MecabTokenizer(mecab_dic='unidic' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = MecabTokenizer(do_lower_case=__a , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def A_ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' try: __snake_case : Union[str, Any] = MecabTokenizer( do_lower_case=__a , normalize_text=__a , mecab_option='-d /usr/local/lib/mecab/dic/jumandic' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '\u3000', '。'] , ) def A_ ( self : Dict ) -> Any: '''simple docstring''' __snake_case : str = MecabTokenizer(normalize_text=__a , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', ' ', '。'] , ) @require_sudachi def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class(self.vocab_file , word_tokenizer_type='sudachi' ) self.assertIsNotNone(__a ) __snake_case : Union[str, Any] = 'こんにちは、世界。\nこんばんは、世界。' __snake_case : Optional[Any] = tokenizer.tokenize(__a ) self.assertListEqual(__a , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __snake_case : List[str] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__a , 'wb' ) as handle: pickle.dump(__a , __a ) with open(__a , 'rb' ) as handle: __snake_case : List[str] = pickle.load(__a ) __snake_case : int = tokenizer_new.tokenize(__a ) self.assertListEqual(__a , __a ) @require_sudachi def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' __snake_case : List[Any] = SudachiTokenizer(sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[int] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='A' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国', '人', '参政', '権'] ) @require_sudachi def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='B' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人', '参政権'] ) @require_sudachi def A_ ( self : str ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='C' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人参政権'] ) @require_sudachi def A_ ( self : Tuple ) -> int: '''simple docstring''' __snake_case : List[Any] = SudachiTokenizer(do_lower_case=__a , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def A_ ( self : Optional[int] ) -> int: '''simple docstring''' __snake_case : Dict = SudachiTokenizer(normalize_text=__a , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' '] , ) @require_sudachi def A_ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = SudachiTokenizer(trim_whitespace=__a , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) @require_jumanpp def A_ ( self : Dict ) -> Dict: '''simple docstring''' __snake_case : int = self.tokenizer_class(self.vocab_file , word_tokenizer_type='jumanpp' ) self.assertIsNotNone(__a ) __snake_case : List[Any] = 'こんにちは、世界。\nこんばんは、世界。' __snake_case : Any = tokenizer.tokenize(__a ) self.assertListEqual(__a , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __snake_case : Optional[Any] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__a , 'wb' ) as handle: pickle.dump(__a , __a ) with open(__a , 'rb' ) as handle: __snake_case : List[str] = pickle.load(__a ) __snake_case : Any = tokenizer_new.tokenize(__a ) self.assertListEqual(__a , __a ) @require_jumanpp def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def A_ ( self : Optional[int] ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = JumanppTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : Dict = JumanppTokenizer(normalize_text=__a ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['ア', 'ッ', 'フ', '゚', 'ル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = JumanppTokenizer(trim_whitespace=__a ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。'] , ) @require_jumanpp def A_ ( self : str ) -> str: '''simple docstring''' __snake_case : Optional[Any] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('ありがとうございますm(_ _)m見つけるのが大変です。' ) , ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。'] , ) def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは'] __snake_case : Any = {} for i, token in enumerate(__a ): __snake_case : str = i __snake_case : List[Any] = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こんにちは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは' ) , ['こん', '##ばんは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは' ) , ['こん', '##ばんは', '[UNK]', 'こんにちは'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp' ) __snake_case : Dict = tokenizer.subword_tokenizer __snake_case : List[str] = subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。' ) self.assertListEqual(__a , ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。'] ) __snake_case : List[Any] = subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは' ) self.assertListEqual(__a , ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは'] ) def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' __snake_case : List[Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese' ) __snake_case : List[Any] = tokenizer.encode('ありがとう。' , add_special_tokens=__a ) __snake_case : str = tokenizer.encode('どういたしまして。' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : Dict = tokenizer.build_inputs_with_special_tokens(__a , __a ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = BertJapaneseTokenizer A__ = False def A_ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' super().setUp() __snake_case : Optional[Any] = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] __snake_case : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : Tuple , **__a : Dict ) -> Union[str, Any]: '''simple docstring''' return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='character' , **__a ) def A_ ( self : Any , __a : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Dict = 'こんにちは、世界。 \nこんばんは、世界。' __snake_case : str = 'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。' return input_text, output_text def A_ ( self : Any ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def A_ ( self : int ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def A_ ( self : List[Any] ) -> int: '''simple docstring''' pass # TODO add if relevant def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : Any = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='character' ) __snake_case : Any = tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。' ) self.assertListEqual( __a , ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def A_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case : Tuple = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] __snake_case : Union[str, Any] = {} for i, token in enumerate(__a ): __snake_case : Union[str, Any] = i __snake_case : int = CharacterTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こ', 'ん', 'に', 'ち', 'は'] ) self.assertListEqual(tokenizer.tokenize('こんにちほ' ) , ['こ', 'ん', 'に', 'ち', '[UNK]'] ) def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char' ) __snake_case : List[str] = tokenizer.encode('ありがとう。' , add_special_tokens=__a ) __snake_case : Union[str, Any] = tokenizer.encode('どういたしまして。' , add_special_tokens=__a ) __snake_case : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : int = tokenizer.build_inputs_with_special_tokens(__a , __a ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class snake_case__ ( unittest.TestCase ): def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cl-tohoku/bert-base-japanese' __snake_case : List[str] = AutoTokenizer.from_pretrained(__a ) self.assertIsInstance(__a , __a ) class snake_case__ ( unittest.TestCase ): def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[int] = 'cl-tohoku/bert-base-japanese' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertTokenizer.from_pretrained(__a ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) ) __snake_case : str = 'bert-base-cased' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertJapaneseTokenizer.from_pretrained(__a ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
1
'''simple docstring''' A__ : Tuple = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def a_ ( _UpperCAmelCase : int ) -> int: __snake_case : Dict = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 10_00_00] number //= 10_00_00 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution A__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 A__ : Optional[Any] = True A__ : int = False def a_ ( _UpperCAmelCase : int ) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore __snake_case : List[str] = chain(next_number(_UpperCAmelCase ) ) __snake_case : Optional[Any] = number_chain while number < 10_00_00_00: __snake_case : Tuple = number_chain number *= 10 return number_chain def a_ ( _UpperCAmelCase : int = 10_00_00_00 ) -> int: for i in range(1 ,_UpperCAmelCase ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
1
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def a_ ( *_UpperCAmelCase : Tuple ) -> List[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : str = list(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : Tuple = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def a_ ( _UpperCAmelCase : Exception ) -> bool: __snake_case : Optional[Any] = [ 'CUDA out of memory.', # CUDA OOM 'cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.', # CUDNN SNAFU 'DefaultCPUAllocator: can\'t allocate memory', # CPU OOM ] if isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def a_ ( _UpperCAmelCase : callable = None ,_UpperCAmelCase : int = 1_28 ) -> List[str]: if function is None: return functools.partial(_UpperCAmelCase ,starting_batch_size=_UpperCAmelCase ) __snake_case : Optional[Any] = starting_batch_size def decorator(*_UpperCAmelCase : Optional[Any] ,**_UpperCAmelCase : int ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() __snake_case : str = list(inspect.signature(_UpperCAmelCase ).parameters.keys() ) # Guard against user error if len(_UpperCAmelCase ) < (len(_UpperCAmelCase ) + 1): __snake_case : Dict = ', '.join([f'''{arg}={value}''' for arg, value in zip(params[1:] ,args[1:] )] ) raise TypeError( f'''Batch size was passed into `{function.__name__}` as the first argument when called.''' f'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError('No executable batch size found, reached zero.' ) try: return function(_UpperCAmelCase ,*_UpperCAmelCase ,**_UpperCAmelCase ) except Exception as e: if should_reduce_batch_size(_UpperCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def a_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Optional[int] = 3_84 __snake_case : str = 7 if "tiny" in model_name: __snake_case : str = 96 __snake_case : Tuple = (2, 2, 6, 2) __snake_case : List[Any] = (3, 6, 12, 24) elif "small" in model_name: __snake_case : List[Any] = 96 __snake_case : Union[str, Any] = (2, 2, 18, 2) __snake_case : int = (3, 6, 12, 24) elif "base" in model_name: __snake_case : Union[str, Any] = 1_28 __snake_case : int = (2, 2, 18, 2) __snake_case : Dict = (4, 8, 16, 32) __snake_case : List[Any] = 12 __snake_case : Optional[int] = 5_12 elif "large" in model_name: __snake_case : Optional[Any] = 1_92 __snake_case : Dict = (2, 2, 18, 2) __snake_case : List[Any] = (6, 12, 24, 48) __snake_case : Union[str, Any] = 12 __snake_case : List[Any] = 7_68 # set label information __snake_case : Optional[int] = 1_50 __snake_case : str = 'huggingface/label-files' __snake_case : List[Any] = 'ade20k-id2label.json' __snake_case : Any = json.load(open(hf_hub_download(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ,'r' ) ) __snake_case : int = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[int] = {v: k for k, v in idalabel.items()} __snake_case : List[Any] = SwinConfig( embed_dim=_UpperCAmelCase ,depths=_UpperCAmelCase ,num_heads=_UpperCAmelCase ,window_size=_UpperCAmelCase ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) __snake_case : str = UperNetConfig( backbone_config=_UpperCAmelCase ,auxiliary_in_channels=_UpperCAmelCase ,num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ,) return config def a_ ( _UpperCAmelCase : Optional[Any] ) -> List[Any]: __snake_case : str = [] # fmt: off # stem rename_keys.append(('backbone.patch_embed.projection.weight', 'backbone.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.projection.bias', 'backbone.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'backbone.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'backbone.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.stages.{i}.downsample.reduction.weight''', f'''backbone.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.weight''', f'''backbone.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.bias''', f'''backbone.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : str ) -> Tuple: __snake_case : List[Any] = dct.pop(_UpperCAmelCase ) __snake_case : str = val def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ) -> str: __snake_case : str = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __snake_case : str = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __snake_case : Optional[Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' ) __snake_case : Tuple = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __snake_case : Any = in_proj_weight[:dim, :] __snake_case : int = in_proj_bias[: dim] __snake_case : str = in_proj_weight[ dim : dim * 2, : ] __snake_case : str = in_proj_bias[ dim : dim * 2 ] __snake_case : Optional[Any] = in_proj_weight[ -dim :, : ] __snake_case : Any = in_proj_bias[-dim :] # fmt: on def a_ ( _UpperCAmelCase : Any ) -> Optional[Any]: __snake_case , __snake_case : Union[str, Any] = x.shape __snake_case : Any = x.reshape(_UpperCAmelCase ,4 ,in_channel // 4 ) __snake_case : str = x[:, [0, 2, 1, 3], :].transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : str ) -> List[Any]: __snake_case , __snake_case : Union[str, Any] = x.shape __snake_case : Tuple = x.reshape(_UpperCAmelCase ,in_channel // 4 ,4 ) __snake_case : Any = x[:, :, [0, 2, 1, 3]].transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : List[str] ) -> List[str]: __snake_case : int = x.shape[0] __snake_case : Optional[Any] = x.reshape(4 ,in_channel // 4 ) __snake_case : int = x[[0, 2, 1, 3], :].transpose(0 ,1 ).reshape(_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : Optional[int] ) -> Any: __snake_case : Tuple = x.shape[0] __snake_case : Tuple = x.reshape(in_channel // 4 ,4 ) __snake_case : Dict = x[:, [0, 2, 1, 3]].transpose(0 ,1 ).reshape(_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ) -> str: __snake_case : Optional[Any] = { 'upernet-swin-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth', 'upernet-swin-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth', 'upernet-swin-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth', 'upernet-swin-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth', } __snake_case : List[str] = model_name_to_url[model_name] __snake_case : str = torch.hub.load_state_dict_from_url(_UpperCAmelCase ,map_location='cpu' ,file_name=_UpperCAmelCase )[ 'state_dict' ] for name, param in state_dict.items(): print(_UpperCAmelCase ,param.shape ) __snake_case : List[str] = get_upernet_config(_UpperCAmelCase ) __snake_case : List[Any] = UperNetForSemanticSegmentation(_UpperCAmelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __snake_case : int = state_dict.pop(_UpperCAmelCase ) if "bn" in key: __snake_case : Tuple = key.replace('bn' ,'batch_norm' ) __snake_case : Union[str, Any] = val # rename keys __snake_case : Any = create_rename_keys(_UpperCAmelCase ) for src, dest in rename_keys: rename_key(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) read_in_q_k_v(_UpperCAmelCase ,config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __snake_case : str = reverse_correct_unfold_reduction_order(_UpperCAmelCase ) if "norm" in key: __snake_case : List[str] = reverse_correct_unfold_norm_order(_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) # verify on image __snake_case : List[str] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' __snake_case : Union[str, Any] = Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ).convert('RGB' ) __snake_case : Tuple = SegformerImageProcessor() __snake_case : str = processor(_UpperCAmelCase ,return_tensors='pt' ).pixel_values with torch.no_grad(): __snake_case : Any = model(_UpperCAmelCase ) __snake_case : Dict = outputs.logits print(logits.shape ) print('First values of logits:' ,logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __snake_case : int = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ) elif model_name == "upernet-swin-small": __snake_case : Any = torch.tensor( [[-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.0_9_0_8, -7.0_9_0_8, -6.8_5_3_4]] ) elif model_name == "upernet-swin-base": __snake_case : Dict = torch.tensor( [[-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.4_7_6_3, -6.4_7_6_3, -6.3_2_5_4]] ) elif model_name == "upernet-swin-large": __snake_case : List[str] = torch.tensor( [[-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.4_0_4_4, -7.4_0_4_4, -7.2_5_8_6]] ) print('Logits:' ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,_UpperCAmelCase ,atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCAmelCase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": A__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-swin-tiny''', type=str, choices=[F"""upernet-swin-{size}""" for size in ['''tiny''', '''small''', '''base''', '''large''']], help='''Name of the Swin + UperNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) A__ : str = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
1
'''simple docstring''' import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : List[Any] , __a : UNetaDModel , __a : UNetaDModel , __a : DDPMScheduler , __a : List[Any] , ) -> int: '''simple docstring''' super().__init__() __snake_case : Tuple = value_function __snake_case : Any = unet __snake_case : Optional[Any] = scheduler __snake_case : str = env __snake_case : str = env.get_dataset() __snake_case : Dict = {} for key in self.data.keys(): try: __snake_case : int = self.data[key].mean() except: # noqa: E722 pass __snake_case : Tuple = {} for key in self.data.keys(): try: __snake_case : List[str] = self.data[key].std() except: # noqa: E722 pass __snake_case : Dict = env.observation_space.shape[0] __snake_case : Optional[int] = env.action_space.shape[0] def A_ ( self : List[Any] , __a : Optional[Any] , __a : Optional[int] ) -> Dict: '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def A_ ( self : Optional[Any] , __a : str , __a : List[str] ) -> List[Any]: '''simple docstring''' return x_in * self.stds[key] + self.means[key] def A_ ( self : int , __a : Optional[Any] ) -> Optional[int]: '''simple docstring''' if type(__a ) is dict: return {k: self.to_torch(__a ) for k, v in x_in.items()} elif torch.is_tensor(__a ): return x_in.to(self.unet.device ) return torch.tensor(__a , device=self.unet.device ) def A_ ( self : Any , __a : Union[str, Any] , __a : List[str] , __a : Optional[Any] ) -> str: '''simple docstring''' for key, val in cond.items(): __snake_case : Dict = val.clone() return x_in def A_ ( self : List[Any] , __a : Dict , __a : Any , __a : int , __a : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = x.shape[0] __snake_case : Any = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model __snake_case : Any = torch.full((batch_size,) , __a , device=self.unet.device , dtype=torch.long ) for _ in range(__a ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __snake_case : Dict = self.value_function(x.permute(0 , 2 , 1 ) , __a ).sample __snake_case : str = torch.autograd.grad([y.sum()] , [x] )[0] __snake_case : Tuple = self.scheduler._get_variance(__a ) __snake_case : List[str] = torch.exp(0.5 * posterior_variance ) __snake_case : Any = model_std * grad __snake_case : str = 0 __snake_case : List[str] = x.detach() __snake_case : Tuple = x + scale * grad __snake_case : Optional[Any] = self.reset_xa(__a , __a , self.action_dim ) __snake_case : Union[str, Any] = self.unet(x.permute(0 , 2 , 1 ) , __a ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg __snake_case : str = self.scheduler.step(__a , __a , __a , predict_epsilon=__a )['prev_sample'] # apply conditions to the trajectory (set the initial state) __snake_case : Optional[int] = self.reset_xa(__a , __a , self.action_dim ) __snake_case : List[Any] = self.to_torch(__a ) return x, y def __call__( self : Tuple , __a : Any , __a : Optional[Any]=64 , __a : List[Any]=32 , __a : Union[str, Any]=2 , __a : Dict=0.1 ) -> List[str]: '''simple docstring''' # normalize the observations and create batch dimension __snake_case : Optional[Any] = self.normalize(__a , 'observations' ) __snake_case : Optional[int] = obs[None].repeat(__a , axis=0 ) __snake_case : Any = {0: self.to_torch(__a )} __snake_case : Dict = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __snake_case : str = randn_tensor(__a , device=self.unet.device ) __snake_case : Any = self.reset_xa(__a , __a , self.action_dim ) __snake_case : List[str] = self.to_torch(__a ) # run the diffusion process __snake_case , __snake_case : Optional[Any] = self.run_diffusion(__a , __a , __a , __a ) # sort output trajectories by value __snake_case : List[str] = y.argsort(0 , descending=__a ).squeeze() __snake_case : List[Any] = x[sorted_idx] __snake_case : Optional[Any] = sorted_values[:, :, : self.action_dim] __snake_case : str = actions.detach().cpu().numpy() __snake_case : List[str] = self.de_normalize(__a , key='actions' ) # select the action with the highest value if y is not None: __snake_case : Any = 0 else: # if we didn't run value guiding, select a random action __snake_case : Tuple = np.random.randint(0 , __a ) __snake_case : Any = denorm_actions[selected_index, 0] return denorm_actions
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() A__ : Union[str, Any] = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> int: __snake_case : List[Any] = UniSpeechSatForSequenceClassification.from_pretrained(_UpperCAmelCase ,config=_UpperCAmelCase ) __snake_case : List[str] = downstream_dict['projector.weight'] __snake_case : int = downstream_dict['projector.bias'] __snake_case : str = downstream_dict['model.post_net.linear.weight'] __snake_case : Tuple = downstream_dict['model.post_net.linear.bias'] return model def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ) -> str: __snake_case : List[Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(_UpperCAmelCase ,config=_UpperCAmelCase ) __snake_case : Optional[Any] = downstream_dict['model.linear.weight'] __snake_case : Union[str, Any] = downstream_dict['model.linear.bias'] return model def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Optional[int] ) -> Tuple: __snake_case : Dict = UniSpeechSatForXVector.from_pretrained(_UpperCAmelCase ,config=_UpperCAmelCase ) __snake_case : List[Any] = downstream_dict['connector.weight'] __snake_case : int = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __snake_case : List[str] = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] __snake_case : int = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] __snake_case : Union[str, Any] = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] __snake_case : Any = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] __snake_case : Union[str, Any] = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] __snake_case : Tuple = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] __snake_case : int = downstream_dict['objective.W'] return model @torch.no_grad() def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int] ) -> Union[str, Any]: __snake_case : int = torch.load(_UpperCAmelCase ,map_location='cpu' ) __snake_case : Union[str, Any] = checkpoint['Downstream'] __snake_case : List[Any] = UniSpeechSatConfig.from_pretrained(_UpperCAmelCase ) __snake_case : List[Any] = WavaVecaFeatureExtractor.from_pretrained( _UpperCAmelCase ,return_attention_mask=_UpperCAmelCase ,do_normalize=_UpperCAmelCase ) __snake_case : Any = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): __snake_case : Optional[Any] = convert_classification(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) elif arch.endswith('ForAudioFrameClassification' ): __snake_case : Optional[int] = convert_diarization(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) elif arch.endswith('ForXVector' ): __snake_case : Tuple = convert_xvector(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: __snake_case : Optional[Any] = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(_UpperCAmelCase ) hf_model.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') A__ : str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1