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""" from numpy import exp, pi, sqrt def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase = 0.0 , _UpperCamelCase = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
86
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin _A : int = """ Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning. In March 2021, Hugging Face raised $40 million in a Series B funding round.[3] On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5] """ class a__ ( unittest.TestCase, a_ ): def __magic_name__ ( self ): lowercase : Tuple = load_tool("text-question-answering" ) self.tool.setup() lowercase : Dict = load_tool("text-question-answering" , remote=_a ) def __magic_name__ ( self ): lowercase : str = self.tool(_a , "What did Hugging Face do in April 2021?" ) self.assertEqual(_a , "launched the BigScience Research Workshop" ) def __magic_name__ ( self ): lowercase : Union[str, Any] = self.remote_tool(_a , "What did Hugging Face do in April 2021?" ) self.assertEqual(_a , "launched the BigScience Research Workshop" ) def __magic_name__ ( self ): lowercase : int = self.tool(text=_a , question="What did Hugging Face do in April 2021?" ) self.assertEqual(_a , "launched the BigScience Research Workshop" ) def __magic_name__ ( self ): lowercase : Optional[Any] = self.remote_tool(text=_a , question="What did Hugging Face do in April 2021?" ) self.assertEqual(_a , "launched the BigScience Research Workshop" )
202
0
class UpperCamelCase__ : def __init__(self : Optional[int] , snake_case_ : int ): __a : List[Any] = n __a : Tuple = [None] * self.n __a : List[Any] = 0 # index of the first element __a : List[str] = 0 __a : Tuple = 0 def __len__(self : List[Any] ): return self.size def lowerCAmelCase (self : Tuple ): return self.size == 0 def lowerCAmelCase (self : Dict ): return False if self.is_empty() else self.array[self.front] def lowerCAmelCase (self : Optional[int] , snake_case_ : int ): if self.size >= self.n: raise Exception('''QUEUE IS FULL''' ) __a : Tuple = data __a : str = (self.rear + 1) % self.n self.size += 1 return self def lowerCAmelCase (self : Optional[int] ): if self.size == 0: raise Exception('''UNDERFLOW''' ) __a : str = self.array[self.front] __a : Union[str, Any] = None __a : Tuple = (self.front + 1) % self.n self.size -= 1 return temp
369
def __UpperCamelCase ( lowerCAmelCase__ : list[list[int | float]] ): __a : int = len(lowerCAmelCase__ ) __a : Dict = len(matrix[0] ) __a : Union[str, Any] = min(lowerCAmelCase__ , lowerCAmelCase__ ) for row in range(lowerCAmelCase__ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , lowerCAmelCase__ ): __a : Dict = matrix[col][row] / matrix[row][row] for i in range(lowerCAmelCase__ , lowerCAmelCase__ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __a : Optional[int] = True for i in range(row + 1 , lowerCAmelCase__ ): if matrix[i][row] != 0: __a , __a : Any = matrix[i], matrix[row] __a : Union[str, Any] = False break if reduce: rank -= 1 for i in range(lowerCAmelCase__ ): __a : Optional[Any] = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
90
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): lowercase : str =UnCLIPImageVariationPipeline lowercase : Optional[Any] =IMAGE_VARIATION_PARAMS - {'height', 'width', 'guidance_scale'} lowercase : List[str] =IMAGE_VARIATION_BATCH_PARAMS lowercase : Optional[int] =[ 'generator', 'return_dict', 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] lowercase : int =False @property def lowercase__ ( self ): """simple docstring""" return 32 @property def lowercase__ ( self ): """simple docstring""" return 32 @property def lowercase__ ( self ): """simple docstring""" return self.time_input_dim @property def lowercase__ ( self ): """simple docstring""" return self.time_input_dim * 4 @property def lowercase__ ( self ): """simple docstring""" return 100 @property def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ =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=1_000, ) return CLIPTextModelWithProjection(lowerCAmelCase ) @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size, projection_dim=self.text_embedder_hidden_size, num_hidden_layers=5, num_attention_heads=4, image_size=32, intermediate_size=37, patch_size=1, ) return CLIPVisionModelWithProjection(lowerCAmelCase ) @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ ={ '''clip_embeddings_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''cross_attention_dim''': self.cross_attention_dim, } lowerCamelCase_ =UnCLIPTextProjModel(**lowerCAmelCase ) return model @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ ={ '''sample_size''': 32, # RGB in channels '''in_channels''': 3, # Out channels is double in channels because predicts mean and variance '''out_channels''': 6, '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': '''identity''', } lowerCamelCase_ =UNetaDConditionModel(**lowerCAmelCase ) return model @property def lowercase__ ( self ): """simple docstring""" return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ =UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(1 ) lowerCamelCase_ =UNetaDModel(**self.dummy_super_res_kwargs ) return model def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.dummy_decoder lowerCamelCase_ =self.dummy_text_proj lowerCamelCase_ =self.dummy_text_encoder lowerCamelCase_ =self.dummy_tokenizer lowerCamelCase_ =self.dummy_super_res_first lowerCamelCase_ =self.dummy_super_res_last lowerCamelCase_ =UnCLIPScheduler( variance_type='''learned_range''', prediction_type='''epsilon''', num_train_timesteps=1_000, ) lowerCamelCase_ =UnCLIPScheduler( variance_type='''fixed_small_log''', prediction_type='''epsilon''', num_train_timesteps=1_000, ) lowerCamelCase_ =CLIPImageProcessor(crop_size=32, size=32 ) lowerCamelCase_ =self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=0, lowerCAmelCase=True ): """simple docstring""" lowerCamelCase_ =floats_tensor((1, 3, 32, 32), rng=random.Random(lowerCAmelCase ) ).to(lowerCAmelCase ) if str(lowerCAmelCase ).startswith('''mps''' ): lowerCamelCase_ =torch.manual_seed(lowerCAmelCase ) else: lowerCamelCase_ =torch.Generator(device=lowerCAmelCase ).manual_seed(lowerCAmelCase ) if pil_image: lowerCamelCase_ =input_image * 0.5 + 0.5 lowerCamelCase_ =input_image.clamp(0, 1 ) lowerCamelCase_ =input_image.cpu().permute(0, 2, 3, 1 ).float().numpy() lowerCamelCase_ =DiffusionPipeline.numpy_to_pil(lowerCAmelCase )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''cpu''' lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =pipe(**lowerCAmelCase ) lowerCamelCase_ =output.images lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =pipe( **lowerCAmelCase, return_dict=lowerCAmelCase, )[0] lowerCamelCase_ =image[0, -3:, -3:, -1] lowerCamelCase_ =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array( [ 0.9_9_9_7, 0.0_0_0_2, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_6_9, 0.0_0_2_3, 0.9_9_9_7, 0.9_9_6_9, 0.9_9_7_0, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''cpu''' lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =pipe(**lowerCAmelCase ) lowerCamelCase_ =output.images lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =pipe( **lowerCAmelCase, return_dict=lowerCAmelCase, )[0] lowerCamelCase_ =image[0, -3:, -3:, -1] lowerCamelCase_ =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.9_9_9_7, 0.0_0_0_3, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_7_0, 0.0_0_2_4, 0.9_9_9_7, 0.9_9_7_1, 0.9_9_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''cpu''' lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =[ pipeline_inputs['''image'''], pipeline_inputs['''image'''], ] lowerCamelCase_ =pipe(**lowerCAmelCase ) lowerCamelCase_ =output.images lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =[ tuple_pipeline_inputs['''image'''], tuple_pipeline_inputs['''image'''], ] lowerCamelCase_ =pipe( **lowerCAmelCase, return_dict=lowerCAmelCase, )[0] lowerCamelCase_ =image[0, -3:, -3:, -1] lowerCamelCase_ =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) lowerCamelCase_ =np.array( [ 0.9_9_9_7, 0.9_9_8_9, 0.0_0_0_8, 0.0_0_2_1, 0.9_9_6_0, 0.0_0_1_8, 0.0_0_1_4, 0.0_0_0_2, 0.9_9_3_3, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =torch.device('''cpu''' ) class __UpperCamelCase : lowercase : Union[str, Any] =1 lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =torch.Generator(device=lowerCAmelCase ).manual_seed(0 ) lowerCamelCase_ =pipe.decoder.dtype lowerCamelCase_ =1 lowerCamelCase_ =( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) lowerCamelCase_ =pipe.prepare_latents( lowerCAmelCase, dtype=lowerCAmelCase, device=lowerCAmelCase, generator=lowerCAmelCase, latents=lowerCAmelCase, scheduler=DummyScheduler() ) lowerCamelCase_ =( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) lowerCamelCase_ =pipe.prepare_latents( lowerCAmelCase, dtype=lowerCAmelCase, device=lowerCAmelCase, generator=lowerCAmelCase, latents=lowerCAmelCase, scheduler=DummyScheduler() ) lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) lowerCamelCase_ =pipe( **lowerCAmelCase, decoder_latents=lowerCAmelCase, super_res_latents=lowerCAmelCase ).images lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase, pil_image=lowerCAmelCase ) # Don't pass image, instead pass embedding lowerCamelCase_ =pipeline_inputs.pop('''image''' ) lowerCamelCase_ =pipe.image_encoder(lowerCAmelCase ).image_embeds lowerCamelCase_ =pipe( **lowerCAmelCase, decoder_latents=lowerCAmelCase, super_res_latents=lowerCAmelCase, image_embeddings=lowerCAmelCase, ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =torch_device == '''cpu''' # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor lowerCamelCase_ =1e-2 self._test_attention_slicing_forward_pass( test_max_difference=lowerCAmelCase, expected_max_diff=lowerCAmelCase ) @skip_mps def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =torch_device == '''cpu''' lowerCamelCase_ =True lowerCamelCase_ =[ '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] self._test_inference_batch_single_identical( test_max_difference=lowerCAmelCase, relax_max_difference=lowerCAmelCase, additional_params_copy_to_batched_inputs=lowerCAmelCase, ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =[ '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes lowerCamelCase_ =[2, 3] self._test_inference_batch_consistent( batch_sizes=lowerCAmelCase, additional_params_copy_to_batched_inputs=lowerCAmelCase, ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=lowerCAmelCase ) @skip_mps def lowercase__ ( self ): """simple docstring""" return super().test_dict_tuple_outputs_equivalent() @skip_mps def lowercase__ ( self ): """simple docstring""" return super().test_save_load_local() @skip_mps def lowercase__ ( self ): """simple docstring""" return super().test_save_load_optional_components() @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def lowercase__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png''' ) lowerCamelCase_ =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/unclip/karlo_v1_alpha_cat_variation_fp16.npy''' ) lowerCamelCase_ =UnCLIPImageVariationPipeline.from_pretrained( '''kakaobrain/karlo-v1-alpha-image-variations''', torch_dtype=torch.floataa ) lowerCamelCase_ =pipeline.to(lowerCAmelCase ) pipeline.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =torch.Generator(device='''cpu''' ).manual_seed(0 ) lowerCamelCase_ =pipeline( lowerCAmelCase, generator=lowerCAmelCase, output_type='''np''', ) lowerCamelCase_ =output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(lowerCAmelCase, lowerCAmelCase, 15 )
75
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _a : str= logging.get_logger(__name__) _a : str= {"vocab_file": "spiece.model"} _a : Tuple= { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } _a : int= { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) _a : Optional[int]= 0 _a : str= 1 _a : Tuple= 2 _a : str= 3 _a : Optional[Any]= 4 class UpperCamelCase ( lowercase ): UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : str = """left""" def __init__(self : List[Any] , _A : List[str] , _A : int=False , _A : Tuple=True , _A : Optional[Any]=False , _A : List[Any]="<s>" , _A : Dict="</s>" , _A : str="<unk>" , _A : Optional[Any]="<sep>" , _A : Optional[Any]="<pad>" , _A : Optional[Any]="<cls>" , _A : Dict="<mask>" , _A : List[Any]=["<eop>", "<eod>"] , _A : Optional[Dict[str, Any]] = None , **_A : List[str] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __snake_case : str = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token __snake_case : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , additional_special_tokens=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __snake_case : Tuple = 3 __snake_case : Optional[int] = do_lower_case __snake_case : Union[str, Any] = remove_space __snake_case : Dict = keep_accents __snake_case : str = vocab_file __snake_case : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(_A) @property def _lowercase (self : Dict) -> List[str]: return len(self.sp_model) def _lowercase (self : Dict) -> Union[str, Any]: __snake_case : str = {self.convert_ids_to_tokens(_A): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self : Union[str, Any]) -> List[str]: __snake_case : Optional[Any] = self.__dict__.copy() __snake_case : Union[str, Any] = None return state def __setstate__(self : Union[str, Any] , _A : Optional[Any]) -> str: __snake_case : Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): __snake_case : List[Any] = {} __snake_case : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _lowercase (self : Any , _A : Tuple) -> List[str]: if self.remove_space: __snake_case : List[Any] = ' '.join(inputs.strip().split()) else: __snake_case : Tuple = inputs __snake_case : int = outputs.replace('``' , '"').replace('\'\'' , '"') if not self.keep_accents: __snake_case : str = unicodedata.normalize('NFKD' , _A) __snake_case : Tuple = ''.join([c for c in outputs if not unicodedata.combining(_A)]) if self.do_lower_case: __snake_case : Union[str, Any] = outputs.lower() return outputs def _lowercase (self : List[Any] , _A : str) -> List[str]: __snake_case : int = self.preprocess_text(_A) __snake_case : Dict = self.sp_model.encode(_A , out_type=_A) __snake_case : Union[str, Any] = [] for piece in pieces: if len(_A) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __snake_case : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_A , '')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __snake_case : List[str] = cur_pieces[1:] else: __snake_case : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(_A) else: new_pieces.append(_A) return new_pieces def _lowercase (self : Union[str, Any] , _A : Union[str, Any]) -> Any: return self.sp_model.PieceToId(_A) def _lowercase (self : Tuple , _A : str) -> Optional[int]: return self.sp_model.IdToPiece(_A) def _lowercase (self : List[str] , _A : Dict) -> List[Any]: __snake_case : str = ''.join(_A).replace(_A , ' ').strip() return out_string def _lowercase (self : Dict , _A : List[int] , _A : bool = False , _A : bool = None , _A : bool = True , **_A : str , ) -> str: __snake_case : Tuple = kwargs.pop('use_source_tokenizer' , _A) __snake_case : Tuple = self.convert_ids_to_tokens(_A , skip_special_tokens=_A) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __snake_case : List[str] = [] __snake_case : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) __snake_case : List[Any] = [] sub_texts.append(_A) else: current_sub_text.append(_A) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens __snake_case : Optional[int] = ''.join(_A) __snake_case : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __snake_case : str = self.clean_up_tokenization(_A) return clean_text else: return text def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : int = [self.sep_token_id] __snake_case : Any = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase (self : List[str] , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A) if token_ids_a is not None: return ([0] * len(_A)) + [1] + ([0] * len(_A)) + [1, 1] return ([0] * len(_A)) + [1, 1] def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : Tuple = [self.sep_token_id] __snake_case : Optional[int] = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def _lowercase (self : Tuple , _A : str , _A : Optional[str] = None) -> Tuple[str]: if not os.path.isdir(_A): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return __snake_case : str = 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 : Tuple = self.sp_model.serialized_model_proto() fi.write(_A) return (out_vocab_file,)
172
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _SCREAMING_SNAKE_CASE = { '''configuration_longt5''': ['''LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongT5Config''', '''LongT5OnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ '''LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LongT5EncoderModel''', '''LongT5ForConditionalGeneration''', '''LongT5Model''', '''LongT5PreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ '''FlaxLongT5ForConditionalGeneration''', '''FlaxLongT5Model''', '''FlaxLongT5PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
217
'''simple docstring''' _SCREAMING_SNAKE_CASE = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def _lowerCAmelCase ( lowerCamelCase_ : dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __lowercase = set() # keep track of all the paths to be checked __lowercase = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue __lowercase = queue.pop(0 ) # get the last node from the path __lowercase = path[-1] if node not in explored: __lowercase = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: __lowercase = list(lowerCamelCase_ ) new_path.append(lowerCamelCase_ ) queue.append(lowerCamelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCamelCase_ ) # in case there's no path between the 2 nodes return [] def _lowerCAmelCase ( lowerCamelCase_ : dict , lowerCamelCase_ : str , lowerCamelCase_ : str ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 __lowercase = [start] __lowercase = set(lowerCamelCase_ ) # Keep tab on distances from `start` node. __lowercase = {start: 0, target: -1} while queue: __lowercase = queue.pop(0 ) if node == target: __lowercase = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCamelCase_ ) queue.append(lowerCamelCase_ ) __lowercase = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
217
1
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("0.12.2"): raise Exception("requires fairseq >= 0.12.2") if version.parse(fairseq.__version__) > version.parse("2"): raise Exception("requires fairseq < v2") logging.set_verbosity_info() SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Dict = "Hello, World!" SCREAMING_SNAKE_CASE : Optional[Any] = "en_XX" def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]: _lowercase : List[Any] = Path('data_bin' ) _lowercase : Optional[int] = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(UpperCAmelCase_ ).parent ) , checkpoint_file=Path(UpperCAmelCase_ ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(UpperCAmelCase_ ) , bpe='sentencepiece' , sentencepiece_model=str(Path(UpperCAmelCase_ ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , ) xmod.eval() # disable dropout print(UpperCAmelCase_ ) _lowercase : Optional[int] = xmod.model.encoder.sentence_encoder _lowercase : Tuple = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: _lowercase : List[str] = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our X-MOD config:' , UpperCAmelCase_ ) _lowercase : Any = XmodForSequenceClassification(UpperCAmelCase_ ) if classification_head else XmodForMaskedLM(UpperCAmelCase_ ) model.eval() # Now let's copy all the weights. # Embeddings _lowercase : int = xmod_sent_encoder.embed_tokens.weight _lowercase : str = xmod_sent_encoder.embed_positions.weight _lowercase : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. _lowercase : Optional[int] = xmod_sent_encoder.layernorm_embedding.weight _lowercase : int = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer _lowercase : str = model.roberta.encoder.layer[i] _lowercase : List[str] = xmod_sent_encoder.layers[i] # self attention _lowercase : List[Any] = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('Dimensions of self-attention weights do not match.' ) _lowercase : List[Any] = xmod_layer.self_attn.q_proj.weight _lowercase : Dict = xmod_layer.self_attn.q_proj.bias _lowercase : Dict = xmod_layer.self_attn.k_proj.weight _lowercase : Tuple = xmod_layer.self_attn.k_proj.bias _lowercase : List[Any] = xmod_layer.self_attn.v_proj.weight _lowercase : Union[str, Any] = xmod_layer.self_attn.v_proj.bias # self-attention output _lowercase : List[Any] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('Dimensions of self-attention output weights do not match.' ) _lowercase : Tuple = xmod_layer.self_attn.out_proj.weight _lowercase : Optional[Any] = xmod_layer.self_attn.out_proj.bias _lowercase : Union[str, Any] = xmod_layer.self_attn_layer_norm.weight _lowercase : List[Any] = xmod_layer.self_attn_layer_norm.bias # intermediate _lowercase : str = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of intermediate weights do not match.' ) _lowercase : List[str] = xmod_layer.fca.weight _lowercase : List[Any] = xmod_layer.fca.bias # output _lowercase : Tuple = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of feed-forward weights do not match.' ) _lowercase : Optional[Any] = xmod_layer.fca.weight _lowercase : List[str] = xmod_layer.fca.bias _lowercase : Optional[int] = xmod_layer.final_layer_norm.weight _lowercase : Dict = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: _lowercase : Any = xmod_layer.adapter_layer_norm.weight _lowercase : Optional[Any] = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('Lists of language adapters do not match.' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): _lowercase : str = bert_output.adapter_modules[lang_code] _lowercase : Dict = xmod_layer.adapter_modules[lang_code] _lowercase : Any = from_adapter.fca.weight _lowercase : int = from_adapter.fca.bias _lowercase : Dict = from_adapter.fca.weight _lowercase : Tuple = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: _lowercase : Any = xmod_sent_encoder.layer_norm.weight _lowercase : List[str] = xmod_sent_encoder.layer_norm.bias if classification_head: _lowercase : Optional[Any] = xmod.model.classification_heads['mnli'].dense.weight _lowercase : Optional[Any] = xmod.model.classification_heads['mnli'].dense.bias _lowercase : List[Any] = xmod.model.classification_heads['mnli'].out_proj.weight _lowercase : Optional[int] = xmod.model.classification_heads['mnli'].out_proj.bias else: # LM Head _lowercase : Optional[Any] = xmod.model.encoder.lm_head.dense.weight _lowercase : str = xmod.model.encoder.lm_head.dense.bias _lowercase : List[Any] = xmod.model.encoder.lm_head.layer_norm.weight _lowercase : List[str] = xmod.model.encoder.lm_head.layer_norm.bias _lowercase : str = xmod.model.encoder.lm_head.weight _lowercase : str = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. _lowercase : Optional[Any] = xmod.encode(UpperCAmelCase_ ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(UpperCAmelCase_ ) _lowercase : Optional[Any] = model(UpperCAmelCase_ )[0] if classification_head: _lowercase : List[str] = xmod.model.classification_heads['mnli'](xmod.extract_features(UpperCAmelCase_ ) ) else: _lowercase : str = xmod.model(UpperCAmelCase_ , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) _lowercase : Tuple = torch.max(torch.abs(our_output - their_output ) ).item() print(F'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 _lowercase : Union[str, Any] = torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1e-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) Path(UpperCAmelCase_ ).mkdir(parents=UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCAmelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xmod_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--classification_head", action="store_true", help="Whether to convert a final classification head." ) SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
21
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig 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 TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A_ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : int=3 , lowercase_ : Dict=32 , lowercase_ : Optional[Any]=3 , lowercase_ : Tuple=10 , lowercase_ : Optional[Any]=[10, 20, 30, 40] , lowercase_ : List[str]=[1, 1, 2, 1] , lowercase_ : Optional[int]=True , lowercase_ : str=True , lowercase_ : Dict="relu" , lowercase_ : Optional[Any]=3 , lowercase_ : List[str]=None , ) -> int: UpperCAmelCase : Dict = parent UpperCAmelCase : Dict = batch_size UpperCAmelCase : Any = image_size UpperCAmelCase : Any = num_channels UpperCAmelCase : List[str] = embeddings_size UpperCAmelCase : str = hidden_sizes UpperCAmelCase : str = depths UpperCAmelCase : Optional[int] = is_training UpperCAmelCase : int = use_labels UpperCAmelCase : Optional[int] = hidden_act UpperCAmelCase : List[Any] = num_labels UpperCAmelCase : Union[str, Any] = scope UpperCAmelCase : Any = len(lowercase_ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase : Any = None if self.use_labels: UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: return ResNetConfig( 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 , image_size=self.image_size , ) def UpperCAmelCase_ ( self : int , lowercase_ : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] ) -> Union[str, Any]: UpperCAmelCase : List[Any] = TFResNetModel(config=lowercase_ ) UpperCAmelCase : int = model(lowercase_ ) # 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 UpperCAmelCase_ ( self : Any , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Optional[int] ) -> List[Any]: UpperCAmelCase : List[Any] = self.num_labels UpperCAmelCase : Union[str, Any] = TFResNetForImageClassification(lowercase_ ) UpperCAmelCase : Any = model(lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[Any] = config_and_inputs UpperCAmelCase : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( _snake_case , _snake_case , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () UpperCAmelCase_ : Dict = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : List[Any] = False UpperCAmelCase_ : str = False UpperCAmelCase_ : Optional[int] = False def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: UpperCAmelCase : Optional[int] = TFResNetModelTester(self ) UpperCAmelCase : Dict = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ ) def UpperCAmelCase_ ( self : str ) -> Any: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: return @unittest.skip(reason='ResNet does not use inputs_embeds' ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: pass @unittest.skip(reason='ResNet does not support input and output embeddings' ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: pass def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: UpperCAmelCase , UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase : List[Any] = model_class(lowercase_ ) UpperCAmelCase : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase : str = [*signature.parameters.keys()] UpperCAmelCase : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: def check_hidden_states_output(lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): UpperCAmelCase : Union[str, Any] = model_class(lowercase_ ) UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(lowercase_ , lowercase_ ) ) UpperCAmelCase : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase : int = self.model_tester.num_stages self.assertEqual(len(lowercase_ ) , expected_num_stages + 1 ) # ResNet'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 // 4, self.model_tester.image_size // 4] , ) UpperCAmelCase , UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase : Tuple = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCAmelCase : List[Any] = layer_type UpperCAmelCase : int = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase : List[Any] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase : str = TFResNetModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def UpperCamelCase( ): UpperCAmelCase : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Any: UpperCAmelCase : Optional[int] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCAmelCase : Any = self.default_image_processor UpperCAmelCase : List[Any] = prepare_img() UpperCAmelCase : Dict = image_processor(images=lowercase_ , return_tensors='tf' ) # forward pass UpperCAmelCase : List[Any] = model(**lowercase_ ) # verify the logits UpperCAmelCase : Optional[Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) UpperCAmelCase : int = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowercase_ , atol=1E-4 ) )
151
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version SCREAMING_SNAKE_CASE : Optional[Any] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class UpperCamelCase : '''simple docstring''' lowercase : Optional[str] =field( default="""cifar10""" , metadata={"""help""": """Name of a dataset from the datasets package"""} ) lowercase : Optional[str] =field( default=lowercase__ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) lowercase : Optional[str] =field( default=lowercase__ , metadata={"""help""": """The column name of the images in the files."""} ) lowercase : Optional[str] =field(default=lowercase__ , metadata={"""help""": """A folder containing the training data."""} ) lowercase : Optional[str] =field(default=lowercase__ , metadata={"""help""": """A folder containing the validation data."""} ) lowercase : Optional[float] =field( default=0.15 , metadata={"""help""": """Percent to split off of train for validation."""} ) lowercase : Optional[int] =field( default=lowercase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) lowercase : Optional[int] =field( default=lowercase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def UpperCamelCase ( self ): lowercase_ :int = {} if self.train_dir is not None: lowercase_ :Union[str, Any] = self.train_dir if self.validation_dir is not None: lowercase_ :int = self.validation_dir lowercase_ :str = data_files if data_files else None @dataclass class UpperCamelCase : '''simple docstring''' lowercase : str =field( default=lowercase__ , metadata={ """help""": ( """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch.""" ) } , ) lowercase : Optional[str] =field( default=lowercase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""} ) lowercase : Optional[str] =field( default=lowercase__ , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) lowercase : Optional[str] =field( default=lowercase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""} ) lowercase : str =field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) lowercase : str =field(default=lowercase__ , metadata={"""help""": """Name or path of preprocessor config."""} ) lowercase : bool =field( default=lowercase__ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) lowercase : float =field( default=0.75 , metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""} ) lowercase : bool =field( default=lowercase__ , metadata={"""help""": """Whether or not to train with normalized pixel values as target."""} ) @dataclass class UpperCamelCase ( lowercase__ ): '''simple docstring''' lowercase : float =field( default=1E-3 , metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""} ) def UpperCamelCase ( _a ) -> int: '''simple docstring''' lowercase_ :Tuple = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def UpperCamelCase ( ) -> Optional[int]: '''simple docstring''' lowercase_ :str = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase_ , lowercase_ , lowercase_ :int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase_ , lowercase_ , lowercase_ :Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mae''' , _a , _a ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() lowercase_ :Dict = training_args.get_process_log_level() logger.setLevel(_a ) transformers.utils.logging.set_verbosity(_a ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. lowercase_ :Optional[int] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowercase_ :List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. lowercase_ :Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. lowercase_ :Dict = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _a ) and data_args.train_val_split > 0.0: lowercase_ :int = ds['''train'''].train_test_split(data_args.train_val_split ) lowercase_ :Tuple = split['''train'''] lowercase_ :Optional[int] = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase_ :int = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: lowercase_ :Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.config_name , **_a ) elif model_args.model_name_or_path: lowercase_ :Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_a ) else: lowercase_ :str = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: lowercase_ :int = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_a ) elif model_args.model_name_or_path: lowercase_ :Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_a ) else: lowercase_ :Optional[Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: lowercase_ :Dict = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) lowercase_ :str = ViTMAEForPreTraining(_a ) if training_args.do_train: lowercase_ :str = ds['''train'''].column_names else: lowercase_ :Tuple = ds['''validation'''].column_names if data_args.image_column_name is not None: lowercase_ :Optional[Any] = data_args.image_column_name elif "image" in column_names: lowercase_ :str = '''image''' elif "img" in column_names: lowercase_ :Any = '''img''' else: lowercase_ :Optional[Any] = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: lowercase_ :int = image_processor.size['''shortest_edge'''] else: lowercase_ :Union[str, Any] = (image_processor.size['''height'''], image_processor.size['''width''']) lowercase_ :List[str] = Compose( [ Lambda(lambda _a : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(_a , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_a ): lowercase_ :List[Any] = [transforms(_a ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: lowercase_ :Tuple = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_a ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: lowercase_ :str = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_a ) # Compute absolute learning rate lowercase_ :Any = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: lowercase_ :str = training_args.base_learning_rate * total_train_batch_size / 2_5_6 # Initialize our trainer lowercase_ :Any = Trainer( model=_a , args=_a , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=_a , data_collator=_a , ) # Training if training_args.do_train: lowercase_ :Any = None if training_args.resume_from_checkpoint is not None: lowercase_ :Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowercase_ :Tuple = last_checkpoint lowercase_ :List[Any] = trainer.train(resume_from_checkpoint=_a ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: lowercase_ :str = trainer.evaluate() trainer.log_metrics('''eval''' , _a ) trainer.save_metrics('''eval''' , _a ) # Write model card and (optionally) push to hub lowercase_ :List[Any] = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**_a ) else: trainer.create_model_card(**_a ) def UpperCamelCase ( _a ) -> str: '''simple docstring''' main() if __name__ == "__main__": main()
252
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase ( self ): lowercase_ :int = logging.get_logger() # the current default level is logging.WARNING lowercase_ :List[str] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(UpperCamelCase_ ) def UpperCamelCase ( self ): lowercase_ :Tuple = logging.get_verbosity() lowercase_ :str = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Tuple = '''Testing 1, 2, 3''' # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , '''''' ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) # restore to the original level logging.set_verbosity(UpperCamelCase_ ) @mockenv(TRANSFORMERS_VERBOSITY='''error''' ) def UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var lowercase_ :Any = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Optional[Any] = os.getenv('''TRANSFORMERS_VERBOSITY''' , UpperCamelCase_ ) lowercase_ :Any = logging.log_levels[env_level_str] lowercase_ :Optional[int] = logging.get_verbosity() self.assertEqual( UpperCamelCase_ , UpperCamelCase_ , f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level lowercase_ :str = '''''' transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY='''super-error''' ) def UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() lowercase_ :Any = logging.logging.getLogger() with CaptureLogger(UpperCamelCase_ ) as cl: # this action activates the env var logging.get_logger('''transformers.models.bart.tokenization_bart''' ) self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error''' , cl.out ) # no need to restore as nothing was changed def UpperCamelCase ( self ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() lowercase_ :Optional[int] = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Any = '''Testing 1, 2, 3''' with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1''' ): # nothing should be logged as env var disables this method with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning_advice(UpperCamelCase_ ) self.assertEqual(cl.out , '''''' ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''''' ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning_advice(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) def UpperCamelCase ( ) -> List[Any]: '''simple docstring''' disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
252
1
from ..utils import DummyObject, requires_backends class A_ ( metaclass=_lowerCamelCase ): lowerCAmelCase__ = ["""speech"""] def __init__(self :int , *_UpperCamelCase :Dict , **_UpperCamelCase :Optional[int] )-> Union[str, Any]: requires_backends(self , ['''speech'''] ) class A_ ( metaclass=_lowerCamelCase ): lowerCAmelCase__ = ["""speech"""] def __init__(self :Union[str, Any] , *_UpperCamelCase :Optional[int] , **_UpperCamelCase :int )-> Dict: requires_backends(self , ['''speech'''] )
117
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration snake_case__ : Union[str, Any] = 500000 snake_case__ , snake_case__ : Optional[Any] = os.path.split(__file__) snake_case__ : List[Any] = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def _a ( lowerCamelCase: datasets.Dataset , **lowerCamelCase: Optional[int] ) -> str: '''simple docstring''' __A = dataset.map(**lowerCamelCase ) @get_duration def _a ( lowerCamelCase: datasets.Dataset , **lowerCamelCase: Optional[int] ) -> str: '''simple docstring''' __A = dataset.filter(**lowerCamelCase ) def _a ( ) -> List[Any]: '''simple docstring''' __A = {'''num examples''': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: __A = datasets.Features({'''text''': datasets.Value('''string''' ), '''numbers''': datasets.Value('''float32''' )} ) __A = generate_example_dataset( os.path.join(lowerCamelCase , '''dataset.arrow''' ) , lowerCamelCase , num_examples=lowerCamelCase ) __A = transformers.AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=lowerCamelCase ) def tokenize(lowerCamelCase: List[str] ): return tokenizer(examples['''text'''] ) __A = map(lowerCamelCase ) __A = map(lowerCamelCase , batched=lowerCamelCase ) __A = map(lowerCamelCase , function=lambda lowerCamelCase : None , batched=lowerCamelCase ) with dataset.formatted_as(type='''numpy''' ): __A = map(lowerCamelCase , function=lambda lowerCamelCase : None , batched=lowerCamelCase ) with dataset.formatted_as(type='''pandas''' ): __A = map(lowerCamelCase , function=lambda lowerCamelCase : None , batched=lowerCamelCase ) with dataset.formatted_as(type='''torch''' , columns='''numbers''' ): __A = map(lowerCamelCase , function=lambda lowerCamelCase : None , batched=lowerCamelCase ) with dataset.formatted_as(type='''tensorflow''' , columns='''numbers''' ): __A = map(lowerCamelCase , function=lambda lowerCamelCase : None , batched=lowerCamelCase ) __A = map(lowerCamelCase , function=lowerCamelCase , batched=lowerCamelCase ) __A = filter(lowerCamelCase ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(lowerCamelCase , '''wb''' ) as f: f.write(json.dumps(lowerCamelCase ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
117
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys a_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
352
"""simple docstring""" def a__ ( __lowercase , __lowercase ) -> float: _validate_point(__lowercase ) _validate_point(__lowercase ) if len(__lowercase ) != len(__lowercase ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(a - b ) for a, b in zip(__lowercase , __lowercase ) ) ) def a__ ( __lowercase ) -> None: if point: if isinstance(__lowercase , __lowercase ): for item in point: if not isinstance(__lowercase , (int, float) ): _A = ( "Expected a list of numbers as input, found " f"""{type(__lowercase ).__name__}""" ) raise TypeError(__lowercase ) else: _A = f"""Expected a list of numbers as input, found {type(__lowercase ).__name__}""" raise TypeError(__lowercase ) else: raise ValueError("Missing an input" ) def a__ ( __lowercase , __lowercase ) -> float: _validate_point(__lowercase ) _validate_point(__lowercase ) if len(__lowercase ) != len(__lowercase ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(x - y ) for x, y in zip(__lowercase , __lowercase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
163
0
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: A_ : Union[str, Any] = None A_ : str = logging.get_logger(__name__) A_ : Dict = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} A_ : Optional[int] = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", }, "tokenizer_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/tokenizer.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/tokenizer.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/tokenizer.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/tokenizer.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/tokenizer.json", }, } # TODO(PVP) - this should be removed in Transformers v5 A_ : Optional[Any] = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } class lowerCamelCase (A__ ): lowerCamelCase__ : Tuple = VOCAB_FILES_NAMES lowerCamelCase__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ : str = ["input_ids", "attention_mask"] lowerCamelCase__ : Optional[int] = TaTokenizer lowerCamelCase__ : List[int] = [] def __init__( self : Optional[int] , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Optional[int]="</s>" , __UpperCAmelCase : Tuple="<unk>" , __UpperCAmelCase : Optional[int]="<pad>" , __UpperCAmelCase : List[str]=1_0_0 , __UpperCAmelCase : Dict=None , **__UpperCAmelCase : Union[str, Any] , ) -> str: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE__ = [F"""<extra_id_{i}>""" for i in range(__UpperCAmelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens SCREAMING_SNAKE_CASE__ = len(set(filter(lambda __UpperCAmelCase : bool("""extra_id_""" in str(__UpperCAmelCase ) ) , __UpperCAmelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , extra_ids=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) SCREAMING_SNAKE_CASE__ = vocab_file SCREAMING_SNAKE_CASE__ = False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ = extra_ids @staticmethod def SCREAMING_SNAKE_CASE ( __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str ) -> Any: if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: SCREAMING_SNAKE_CASE__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F""" {pretrained_model_name_or_path} automatically truncating your input to""" F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __UpperCAmelCase , ) return max_model_length def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE__ = os.path.join( __UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) logger.info(F"""Copy vocab file to {out_vocab_file}""" ) return (out_vocab_file,) def SCREAMING_SNAKE_CASE ( self : str , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: SCREAMING_SNAKE_CASE__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def SCREAMING_SNAKE_CASE ( self : Optional[int] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: return list( set(filter(lambda __UpperCAmelCase : bool(re.search(r"""<extra_id_\d+>""" , __UpperCAmelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: return [self.convert_tokens_to_ids(__UpperCAmelCase ) for token in self.get_sentinel_tokens()]
165
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer snake_case_ : List[str] = logging.get_logger(__name__) snake_case_ : Union[str, Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} snake_case_ : Optional[int] = { "vocab_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json" ), }, } snake_case_ : Optional[Any] = { "yjernite/retribert-base-uncased": 5_12, } snake_case_ : Union[str, Any] = { "yjernite/retribert-base-uncased": {"do_lower_case": True}, } class __a (lowerCamelCase ): __a : Optional[Any] = VOCAB_FILES_NAMES __a : Dict = PRETRAINED_VOCAB_FILES_MAP __a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : int = PRETRAINED_INIT_CONFIGURATION __a : Union[str, Any] = RetriBertTokenizer __a : Optional[int] = ["input_ids", "attention_mask"] def __init__( self : str , __magic_name__ : List[Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Any=True , __magic_name__ : int="[UNK]" , __magic_name__ : List[Any]="[SEP]" , __magic_name__ : List[Any]="[PAD]" , __magic_name__ : Optional[int]="[CLS]" , __magic_name__ : Union[str, Any]="[MASK]" , __magic_name__ : int=True , __magic_name__ : Optional[Any]=None , **__magic_name__ : Any , ) -> List[str]: """simple docstring""" super().__init__( __magic_name__ , tokenizer_file=__magic_name__ , do_lower_case=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , pad_token=__magic_name__ , cls_token=__magic_name__ , mask_token=__magic_name__ , tokenize_chinese_chars=__magic_name__ , strip_accents=__magic_name__ , **__magic_name__ , ) UpperCAmelCase_ : str = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __magic_name__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , __magic_name__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __magic_name__ ) != tokenize_chinese_chars ): UpperCAmelCase_ : Dict = getattr(__magic_name__ , normalizer_state.pop('''type''' ) ) UpperCAmelCase_ : Optional[int] = do_lower_case UpperCAmelCase_ : Optional[int] = strip_accents UpperCAmelCase_ : Tuple = tokenize_chinese_chars UpperCAmelCase_ : Optional[int] = normalizer_class(**__magic_name__ ) UpperCAmelCase_ : List[str] = do_lower_case def UpperCAmelCase__ ( self : int , __magic_name__ : List[str] , __magic_name__ : Optional[Any]=None ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : str = [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 UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : Dict = [self.sep_token_id] UpperCAmelCase_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : int = self._tokenizer.model.save(__magic_name__ , name=__magic_name__ ) return tuple(__magic_name__ )
125
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class _lowerCAmelCase ( __snake_case ): '''simple docstring''' lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None class _lowerCAmelCase ( __snake_case , __snake_case ): '''simple docstring''' lowerCAmelCase_ = 2 @register_to_config def __init__(self , UpperCAmelCase = 0.02 , UpperCAmelCase = 100 , UpperCAmelCase = 1.007 , UpperCAmelCase = 80 , UpperCAmelCase = 0.05 , UpperCAmelCase = 50 , ) -> Any: # standard deviation of the initial noise distribution _snake_case = sigma_max # setable values _snake_case = None _snake_case = None _snake_case = None # sigma(t_i) def lowercase (self , UpperCAmelCase , UpperCAmelCase = None ) -> torch.FloatTensor: return sample def lowercase (self , UpperCAmelCase , UpperCAmelCase = None ) -> Tuple: _snake_case = num_inference_steps _snake_case = np.arange(0 , self.num_inference_steps )[::-1].copy() _snake_case = torch.from_numpy(UpperCAmelCase ).to(UpperCAmelCase ) _snake_case = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] _snake_case = torch.tensor(UpperCAmelCase , dtype=torch.floataa , device=UpperCAmelCase ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None ) -> Tuple[torch.FloatTensor, float]: if self.config.s_min <= sigma <= self.config.s_max: _snake_case = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: _snake_case = 0 # sample eps ~ N(0, S_noise^2 * I) _snake_case = self.config.s_noise * randn_tensor(sample.shape , generator=UpperCAmelCase ).to(sample.device ) _snake_case = sigma + gamma * sigma _snake_case = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: _snake_case = sample_hat + sigma_hat * model_output _snake_case = (sample_hat - pred_original_sample) / sigma_hat _snake_case = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: _snake_case = sample_prev + sigma_prev * model_output _snake_case = (sample_prev - pred_original_sample) / sigma_prev _snake_case = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> str: raise NotImplementedError()
270
'''simple docstring''' from random import randint, random def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = 5 , ): _snake_case = [[-1] * number_of_cells] # Create a highway without any car _snake_case = 0 _snake_case = max(_SCREAMING_SNAKE_CASE , 0 ) while i < number_of_cells: _snake_case = ( randint(0 , _SCREAMING_SNAKE_CASE ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = 0 _snake_case = highway_now[car_index + 1 :] for cell in range(len(_SCREAMING_SNAKE_CASE ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(_SCREAMING_SNAKE_CASE , -1 ) def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = len(_SCREAMING_SNAKE_CASE ) # Beforce calculations, the highway is empty _snake_case = [-1] * number_of_cells for car_index in range(_SCREAMING_SNAKE_CASE ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _snake_case = min(highway_now[car_index] + 1 , _SCREAMING_SNAKE_CASE ) # Number of empty cell before the next car _snake_case = get_distance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - 1 # We can't have the car causing an accident _snake_case = min(next_highway[car_index] , _SCREAMING_SNAKE_CASE ) if random() < probability: # Randomly, a driver will slow down _snake_case = max(next_highway[car_index] - 1 , 0 ) return next_highway def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _snake_case = len(highway[0] ) for i in range(_SCREAMING_SNAKE_CASE ): _snake_case = update(highway[i] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _snake_case = [-1] * number_of_cells for car_index in range(_SCREAMING_SNAKE_CASE ): _snake_case = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _snake_case = (car_index + speed) % number_of_cells # Commit the change of position _snake_case = speed highway.append(_SCREAMING_SNAKE_CASE ) return highway if __name__ == "__main__": import doctest doctest.testmod()
270
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __snake_case : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : List[str] = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys __snake_case : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
269
"""simple docstring""" def _lowercase ( ) -> int: return 1 def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else five_pence(x - 5 ) + two_pence(__snake_case ) def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(__snake_case ) def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(__snake_case ) def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(__snake_case ) def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(__snake_case ) def _lowercase ( __snake_case ) -> int: return 0 if x < 0 else two_pound(x - 200 ) + one_pound(__snake_case ) def _lowercase ( __snake_case = 200 ) -> int: return two_pound(__snake_case ) if __name__ == "__main__": print(solution(int(input().strip())))
269
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class a ( _lowerCAmelCase ): @staticmethod @abstractmethod def _UpperCAmelCase ( A_ ): '''simple docstring''' raise NotImplementedError() @abstractmethod def _UpperCAmelCase ( self ): '''simple docstring''' raise NotImplementedError()
370
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str , lowerCAmelCase: float | Decimal , lowerCAmelCase: float = 10**-10 ) -> float: _UpperCAmelCase : Optional[int] = a while True: _UpperCAmelCase : Tuple = Decimal(lowerCAmelCase ) - ( Decimal(eval(lowerCAmelCase ) ) / Decimal(eval(str(diff(lowerCAmelCase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(lowerCAmelCase ) ) < precision: # noqa: S307 return float(lowerCAmelCase ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}''') # Find root of polynomial print(F'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}''') # Find Square Root of 5 print(F'''The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}''') # Exponential Roots print(F'''The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}''')
189
0
from __future__ import annotations def lowerCAmelCase_ ( __A ) -> list[int]: '''simple docstring''' return [ord(__A ) - 96 for elem in plain] def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' return "".join(chr(elem + 96 ) for elem in encoded ) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase__ = encode(input("-> " ).strip().lower() ) print("Encoded: ", __A ) print("Decoded:", decode(__A ) ) if __name__ == "__main__": main()
65
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
def __lowercase ( a__ ) -> int: if not head: return True # split the list to two parts __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = head.next, head while fast and fast.next: __SCREAMING_SNAKE_CASE = fast.next.next __SCREAMING_SNAKE_CASE = slow.next __SCREAMING_SNAKE_CASE = slow.next __SCREAMING_SNAKE_CASE = None # Don't forget here! But forget still works! # reverse the second part __SCREAMING_SNAKE_CASE = None while second: __SCREAMING_SNAKE_CASE = second.next __SCREAMING_SNAKE_CASE = node __SCREAMING_SNAKE_CASE = second __SCREAMING_SNAKE_CASE = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False __SCREAMING_SNAKE_CASE = node.next __SCREAMING_SNAKE_CASE = head.next return True def __lowercase ( a__ ) -> List[str]: if not head or not head.next: return True # 1. Get the midpoint (slow) __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = head while fast and fast.next: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = fast.next.next, slow.next # 2. Push the second half into the stack __SCREAMING_SNAKE_CASE = [slow.val] while slow.next: __SCREAMING_SNAKE_CASE = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False __SCREAMING_SNAKE_CASE = cur.next return True def __lowercase ( a__ ) -> List[str]: if not head or not head.next: return True __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 0 while head: if head.val in d: d[head.val].append(a__ ) else: __SCREAMING_SNAKE_CASE = [pos] __SCREAMING_SNAKE_CASE = head.next pos += 1 __SCREAMING_SNAKE_CASE = pos - 1 __SCREAMING_SNAKE_CASE = 0 for v in d.values(): if len(a__ ) % 2 != 0: middle += 1 else: __SCREAMING_SNAKE_CASE = 0 for i in range(0 , len(a__ ) ): if v[i] + v[len(a__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
350
import os def __lowercase ( a__ = "input.txt" ) -> int: with open(os.path.join(os.path.dirname(a__ ) , a__ ) ) as input_file: __SCREAMING_SNAKE_CASE = [ [int(a__ ) for element in line.split(',' )] for line in input_file.readlines() ] __SCREAMING_SNAKE_CASE = len(a__ ) __SCREAMING_SNAKE_CASE = len(matrix[0] ) __SCREAMING_SNAKE_CASE = [[-1 for _ in range(a__ )] for _ in range(a__ )] for i in range(a__ ): __SCREAMING_SNAKE_CASE = matrix[i][0] for j in range(1 , a__ ): for i in range(a__ ): __SCREAMING_SNAKE_CASE = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , a__ ): __SCREAMING_SNAKE_CASE = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): __SCREAMING_SNAKE_CASE = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F'''{solution() = }''')
118
0
import math import unittest def __magic_name__ ( A : int ): '''simple docstring''' assert isinstance(A, A ) 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 number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(A ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class snake_case__ (unittest.TestCase ): """simple docstring""" def __UpperCAmelCase ( self : List[Any] ) -> Optional[int]: self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: with self.assertRaises(__lowerCamelCase ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , "Zero doesn't have any positive factors, primes must have exactly two." , ) self.assertFalse( is_prime(1 ) , "One only has 1 positive factor, primes must have exactly two." , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
107
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __lowerCAmelCase : List[Any] = '0.12' # assumed parallelism: 8 if is_torch_available(): import torch def __magic_name__ ( A : Dict, A : Union[str, Any], A : Optional[int]=None ): '''simple docstring''' if rng is None: a = random.Random() a = 1 for dim in shape: total_dims *= dim a = [] for _ in range(A ): values.append(rng.randint(0, vocab_size - 1 ) ) a = np.array(A, dtype=jnp.intaa ).reshape(A ) return output def __magic_name__ ( A : Dict, A : Union[str, Any]=None ): '''simple docstring''' a = ids_tensor(A, vocab_size=2, rng=A ) # make sure that at least one token is attended to for each batch a = 1 return attn_mask @require_flax class snake_case__ : """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : Any = () def __UpperCAmelCase ( self : int ) -> List[str]: a , a = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 a = 2 a = inputs["input_ids"].shape[-1] // 2 a = inputs["input_ids"][:max_batch_size, :sequence_length] a = jnp.ones_like(__lowerCamelCase ) a = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens a = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` a = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def __UpperCAmelCase ( self : Optional[Any] ) -> int: a , a , a , a = self._get_input_ids_and_config() a = False a = max_length a = 0 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model_class.__name__[4:] # Skip the "Flax" at the beginning a = getattr(__lowerCamelCase , __lowerCamelCase ) a = pt_model_class(__lowerCamelCase ).eval() a = load_flax_weights_in_pytorch_model(__lowerCamelCase , flax_model.params ) a = flax_model.generate(__lowerCamelCase ).sequences a = pt_model.generate(torch.tensor(__lowerCamelCase , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: a = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def __UpperCAmelCase ( self : List[str] ) -> Optional[int]: a , a , a , a = self._get_input_ids_and_config() a = False a = max_length for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Optional[int] ) -> Any: a , a , a , a = self._get_input_ids_and_config() a = True a = max_length for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : int ) -> Dict: a , a , a , a = self._get_input_ids_and_config() a = False a = max_length a = 2 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Any ) -> Union[str, Any]: a , a , a , a = self._get_input_ids_and_config() a = False a = max_length a = 2 a = 2 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def __UpperCAmelCase ( self : Optional[Any] ) -> Dict: a , a , a , a = self._get_input_ids_and_config() a = True a = max_length a = 0.8 a = 10 a = 0.3 a = 1 a = 8 a = 9 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Optional[Any] ) -> Optional[Any]: a , a , a , a = self._get_input_ids_and_config() a = max_length a = 1 a = 8 a = 9 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : List[str] ) -> Union[str, Any]: a , a , a , a = self._get_input_ids_and_config() a = max_length a = 2 a = 1 a = 8 a = 9 for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Dict: a , a , a , a = self._get_input_ids_and_config() # pad attention mask on the left a = attention_mask.at[(0, 0)].set(0 ) a = False a = max_length for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Tuple ) -> Tuple: a , a , a , a = self._get_input_ids_and_config() # pad attention mask on the left a = attention_mask.at[(0, 0)].set(0 ) a = True a = max_length for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCAmelCase ( self : Optional[int] ) -> List[Any]: a , a , a , a = self._get_input_ids_and_config() # pad attention mask on the left a = attention_mask.at[(0, 0)].set(0 ) a = 2 a = max_length for model_class in self.all_generative_model_classes: a = model_class(__lowerCamelCase ) a = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) a = jit(model.generate ) a = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class snake_case__ (unittest.TestCase ): """simple docstring""" def __UpperCAmelCase ( self : Dict ) -> Optional[Any]: a = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" ) a = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) a = "Hello world" a = tokenizer(__lowerCamelCase , return_tensors="np" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__lowerCamelCase , "do_samples" ): model.generate(__lowerCamelCase , do_samples=__lowerCamelCase ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__lowerCamelCase , "foo" ): a = {"foo": "bar"} model.generate(__lowerCamelCase , **__lowerCamelCase )
107
1
"""simple docstring""" import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowercase ( a__ : List[str] , a__ : Optional[int] , a__ : Tuple ) -> Tuple: if openai_config_file == "": _UpperCamelCase = OpenAIGPTConfig() else: _UpperCamelCase = OpenAIGPTConfig.from_json_file(a__ ) _UpperCamelCase = OpenAIGPTModel(a__ ) # Load weights from numpy load_tf_weights_in_openai_gpt(a__ , a__ , a__ ) # Save pytorch-model _UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME _UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() , a__ ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--openai_checkpoint_folder_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--openai_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
354
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example UpperCAmelCase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example UpperCAmelCase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowercase ( a__ : list[list[int]] ) -> list[list[int]]: _UpperCamelCase = [] for i in range(len(a__ ) ): _UpperCamelCase = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours _UpperCamelCase = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(a__ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(a__ ) - 1: neighbour_count += cells[i + 1][j] if i < len(a__ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. _UpperCamelCase = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(a__ ) return next_generation def lowercase ( a__ : list[list[int]] , a__ : int ) -> list[Image.Image]: _UpperCamelCase = [] for _ in range(a__ ): # Create output image _UpperCamelCase = Image.new('''RGB''' , (len(cells[0] ), len(a__ )) ) _UpperCamelCase = img.load() # Save cells to image for x in range(len(a__ ) ): for y in range(len(cells[0] ) ): _UpperCamelCase = 255 - cells[y][x] * 255 _UpperCamelCase = (colour, colour, colour) # Save image images.append(a__ ) _UpperCamelCase = new_generation(a__ ) return images if __name__ == "__main__": UpperCAmelCase = generate_images(GLIDER, 16) images[0].save("""out.gif""", save_all=True, append_images=images[1:])
54
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig class __A ( UpperCAmelCase__ ): '''simple docstring''' lowerCAmelCase : List[str] = """bert-generation""" def __init__( self : Any ,_snake_case : Tuple=50_358 ,_snake_case : Union[str, Any]=1_024 ,_snake_case : Any=24 ,_snake_case : Optional[Any]=16 ,_snake_case : Tuple=4_096 ,_snake_case : Optional[Any]="gelu" ,_snake_case : Tuple=0.1 ,_snake_case : Optional[int]=0.1 ,_snake_case : Dict=512 ,_snake_case : Union[str, Any]=0.02 ,_snake_case : Optional[Any]=1e-12 ,_snake_case : Optional[Any]=0 ,_snake_case : int=2 ,_snake_case : Tuple=1 ,_snake_case : int="absolute" ,_snake_case : Tuple=True ,**_snake_case : Optional[Any] ,) -> Tuple: """simple docstring""" super().__init__(pad_token_id=__lowercase ,bos_token_id=__lowercase ,eos_token_id=__lowercase ,**__lowercase ) lowercase__ : List[str] = vocab_size lowercase__ : Any = hidden_size lowercase__ : List[Any] = num_hidden_layers lowercase__ : str = num_attention_heads lowercase__ : Optional[Any] = hidden_act lowercase__ : Tuple = intermediate_size lowercase__ : int = hidden_dropout_prob lowercase__ : Optional[int] = attention_probs_dropout_prob lowercase__ : Any = max_position_embeddings lowercase__ : List[Any] = initializer_range lowercase__ : Dict = layer_norm_eps lowercase__ : Optional[Any] = position_embedding_type lowercase__ : Dict = use_cache
16
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class snake_case__( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = JukeboxTokenizer SCREAMING_SNAKE_CASE__ : int = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def lowercase_ ( self ) -> Union[str, Any]: import torch lowerCAmelCase_ : Union[str, Any] = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) lowerCAmelCase_ : Any = tokenizer(**self.metas )['''input_ids'''] # fmt: off lowerCAmelCase_ : List[str] = [ torch.tensor([[ 0, 0, 0, 7_1_6_9, 5_0_7, 9, 7_6, 3_9, 3_1, 4_6, 7_6, 2_7, 7_6, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_6, 3_2, 4_4, 4_1, 3_9, 7_6, 2_7, 4_0, 7_6, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_6, 3_8, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 4_1, 7_6, 4_5, 2_7, 3_5, 3_0, 7_6, 7_1, 2_0, 4_9, 4_1, 7_6, 4_8, 2_7, 4_5, 4_6, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_6, 3_8, 3_1, 3_3, 4_5, 7_6, 4_1, 3_2, 7_6, 4_5, 4_6, 4_1, 4_0, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_9, 4_6, 2_7, 4_0, 3_0, 7_6, 3_5, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 1_4, 3_1, 2_7, 4_4, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_5, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 8, 2_7, 3_8, 3_2, 7_6, 4_5, 4_7, 4_0, 3_7, 7_6, 2_7, 7_6, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_6, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_6, 3_8, 3_5, 3_1, 4_5, 6_4, 7_6, 4_9, 3_4, 4_1, 4_5, 3_1, 7_6, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_6, 3_8, 3_5, 4_2, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_5, 4_0, 3_1, 3_1, 4_4, 7_6, 4_1, 3_2, 7_6, 2_9, 4_1, 3_8, 3_0, 7_6, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_5, 4_6, 4_5, 7_6, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_6, 4_9, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 4_1, 4_5, 3_1, 7_6, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_6, 4_4, 3_1, 2_7, 3_0, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 3_5, 2_9, 3_4, 7_6, 5_1, 3_1, 4_6, 7_6, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_6, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_6, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_4, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_4, 3_1, 2_7, 4_4, 4_6, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_2, 3_1, 3_0, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 4_9, 4_1, 4_4, 3_0, 4_5, 7_6, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_3, 5_1, 7_6, 4_0, 2_7, 3_9, 3_1, 7_6, 3_5, 4_5, 7_6, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_6, 1_1, 3_5, 4_0, 3_3, 7_6, 4_1, 3_2, 7_6, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_2, 4_1, 4_1, 3_7, 7_6, 4_1, 4_0, 7_6, 3_9, 5_1, 7_6, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_6, 5_1, 3_1, 7_6, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_6, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_6, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_6, 1_8, 4_1, 4_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 2_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_5, 3_2, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_6, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_6, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_6, 2_7, 4_0, 3_0, 7_6, 2_8, 2_7, 4_4, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_8, 4_1, 4_0, 3_1, 7_6, 2_7, 4_0, 3_0, 7_6, 3_8, 3_1, 4_8, 3_1, 3_8, 7_6, 4_5, 2_7, 4_0, 3_0, 4_5, 7_6, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_6, 3_2, 2_7, 4_4, 7_6, 2_7, 4_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def lowercase_ ( self ) -> List[Any]: import torch lowerCAmelCase_ : Any = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) lowerCAmelCase_ : str = tokenizer(**self.metas )['''input_ids'''] # fmt: off lowerCAmelCase_ : Tuple = [ torch.tensor([[ 0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1, 9, 7_7, 3_9, 3_1, 4_6, 7_7, 2_7, 7_7, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_7, 3_2, 4_4, 4_1, 3_9, 7_7, 2_7, 4_0, 7_7, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_7, 3_8, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 4_1, 7_7, 4_5, 2_7, 3_5, 3_0, 7_7, 7_2, 2_0, 4_9, 4_1, 7_7, 4_8, 2_7, 4_5, 4_6, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_7, 3_8, 3_1, 3_3, 4_5, 7_7, 4_1, 3_2, 7_7, 4_5, 4_6, 4_1, 4_0, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_9, 4_6, 2_7, 4_0, 3_0, 7_7, 3_5, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 1_4, 3_1, 2_7, 4_4, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_5, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 8, 2_7, 3_8, 3_2, 7_7, 4_5, 4_7, 4_0, 3_7, 7_7, 2_7, 7_7, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_7, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_7, 3_8, 3_5, 3_1, 4_5, 6_4, 7_7, 4_9, 3_4, 4_1, 4_5, 3_1, 7_7, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_7, 3_8, 3_5, 4_2, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_5, 4_0, 3_1, 3_1, 4_4, 7_7, 4_1, 3_2, 7_7, 2_9, 4_1, 3_8, 3_0, 7_7, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_5, 4_6, 4_5, 7_7, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_7, 4_9, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 4_1, 4_5, 3_1, 7_7, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_7, 4_4, 3_1, 2_7, 3_0, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 3_5, 2_9, 3_4, 7_7, 5_1, 3_1, 4_6, 7_7, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_7, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_7, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_4, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_4, 3_1, 2_7, 4_4, 4_6, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_2, 3_1, 3_0, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 4_9, 4_1, 4_4, 3_0, 4_5, 7_7, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_3, 5_1, 7_7, 4_0, 2_7, 3_9, 3_1, 7_7, 3_5, 4_5, 7_7, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_7, 1_1, 3_5, 4_0, 3_3, 7_7, 4_1, 3_2, 7_7, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_2, 4_1, 4_1, 3_7, 7_7, 4_1, 4_0, 7_7, 3_9, 5_1, 7_7, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_7, 5_1, 3_1, 7_7, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_7, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_7, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_7, 1_8, 4_1, 4_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 2_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_5, 3_2, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_7, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_7, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_7, 2_7, 4_0, 3_0, 7_7, 2_8, 2_7, 4_4, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_8, 4_1, 4_0, 3_1, 7_7, 2_7, 4_0, 3_0, 7_7, 3_8, 3_1, 4_8, 3_1, 3_8, 7_7, 4_5, 2_7, 4_0, 3_0, 4_5, 7_7, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_7, 3_2, 2_7, 4_4, 7_7, 2_7, 4_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
262
0
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class A ( unittest.TestCase , A_ ): def _A (self ): __lowercase= load_tool('text-classification' ) self.tool.setup() __lowercase= load_tool('text-classification' , remote=lowerCAmelCase ) def _A (self ): __lowercase= self.tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(lowerCAmelCase , 'positive' ) def _A (self ): __lowercase= self.remote_tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(lowerCAmelCase , 'positive' ) def _A (self ): __lowercase= self.tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(lowerCAmelCase , 'positive' ) def _A (self ): __lowercase= self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(lowerCAmelCase , 'positive' )
353
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass lowerCAmelCase = (3, 9, -1_1, 0, 7, 5, 1, -1) lowerCAmelCase = (4, 6, 2, 0, 8, 1_0, 3, -2) @dataclass class A : UpperCamelCase_ : int UpperCamelCase_ : Node | None class A : def __init__(self , lowerCAmelCase ): __lowercase= None for i in sorted(lowerCAmelCase , reverse=lowerCAmelCase ): __lowercase= Node(lowerCAmelCase , self.head ) def __iter__(self ): __lowercase= self.head while node: yield node.data __lowercase= node.next_node def __len__(self ): return sum(1 for _ in self ) def __str__(self ): return " -> ".join([str(lowerCAmelCase ) for node in self] ) def _lowerCamelCase( lowercase__ , lowercase__ ) -> SortedLinkedList: '''simple docstring''' return SortedLinkedList(list(lowercase__ ) + list(lowercase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
304
0
'''simple docstring''' def _lowerCamelCase ( lowercase : float , lowercase : int ) -> float: if digit_amount > 0: return round(number - int(lowercase ) , lowercase ) return number - int(lowercase ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
63
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> List[Any]: print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: lowercase__ : str = [[float('''inf''' ) for _ in range(__lowerCamelCase )] for _ in range(__lowerCamelCase )] for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): lowercase__ : List[str] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(__lowerCamelCase ): # looping through rows of graph array for i in range(__lowerCamelCase ): # looping through columns of graph array for j in range(__lowerCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): lowercase__ : str = dist[i][k] + dist[k][j] _print_dist(__lowerCamelCase , __lowerCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('Enter number of vertices: ')) lowerCAmelCase_ = int(input('Enter number of edges: ')) lowerCAmelCase_ = [[float('inf') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('\nEdge ', i + 1) lowerCAmelCase_ = int(input('Enter source:')) lowerCAmelCase_ = int(input('Enter destination:')) lowerCAmelCase_ = float(input('Enter weight:')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
16
0
def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" return int((input_a, input_a).count(0 ) == 0 ) def __lowerCamelCase ( ): """simple docstring""" assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
121
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class snake_case__(unittest.TestCase ): """simple docstring""" @property def snake_case ( self : Any ): torch.manual_seed(0 ) lowercase__ : Tuple = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model @property def snake_case ( self : List[str] ): torch.manual_seed(0 ) lowercase__ : Optional[int] = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=3 , ) return model @property def snake_case ( self : Dict ): torch.manual_seed(0 ) lowercase__ : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE ) def snake_case ( self : str ): lowercase__ : Any = self.dummy_uncond_unet lowercase__ : Dict = DDIMScheduler() lowercase__ : Optional[Any] = self.dummy_vq_model lowercase__ : Union[str, Any] = LDMPipeline(unet=SCREAMING_SNAKE_CASE , vqvae=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) ldm.to(SCREAMING_SNAKE_CASE ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) lowercase__ : int = torch.manual_seed(0 ) lowercase__ : Optional[int] = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="numpy" ).images lowercase__ : str = torch.manual_seed(0 ) lowercase__ : List[Any] = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="numpy" , return_dict=SCREAMING_SNAKE_CASE )[0] lowercase__ : Any = image[0, -3:, -3:, -1] lowercase__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowercase__ : List[Any] = np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172] ) lowercase__ : Optional[Any] = 1E-2 if torch_device != "mps" else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class snake_case__(unittest.TestCase ): """simple docstring""" def snake_case ( self : Optional[Any] ): lowercase__ : int = LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256" ) ldm.to(SCREAMING_SNAKE_CASE ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) lowercase__ : Dict = torch.manual_seed(0 ) lowercase__ : Tuple = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , output_type="numpy" ).images lowercase__ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowercase__ : Optional[Any] = np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447] ) lowercase__ : int = 1E-2 if torch_device != "mps" else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
121
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class A ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = tempfile.mkdtemp() lowerCAmelCase_ = SamImageProcessor() lowerCAmelCase_ = SamProcessor(UpperCamelCase__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self, **UpperCamelCase__ ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **UpperCamelCase__ ).image_processor def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] lowerCAmelCase_ = [Image.fromarray(np.moveaxis(UpperCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase_ = self.get_image_processor(do_normalize=UpperCamelCase__, padding_value=1.0 ) lowerCAmelCase_ = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=UpperCamelCase__, padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = self.prepare_image_inputs() lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''np''' ) lowerCAmelCase_ = processor(images=UpperCamelCase__, return_tensors='''np''' ) input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('''reshaped_input_sizes''' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2 ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = [torch.ones((1, 3, 5, 5) )] lowerCAmelCase_ = [[1764, 2646]] lowerCAmelCase_ = [[683, 1024]] lowerCAmelCase_ = processor.post_process_masks(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, torch.tensor(UpperCamelCase__ ), torch.tensor(UpperCamelCase__ ) ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) # should also work with np lowerCAmelCase_ = [np.ones((1, 3, 5, 5) )] lowerCAmelCase_ = processor.post_process_masks(UpperCamelCase__, np.array(UpperCamelCase__ ), np.array(UpperCamelCase__ ) ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) lowerCAmelCase_ = [[1, 0], [0, 1]] with self.assertRaises(UpperCamelCase__ ): lowerCAmelCase_ = processor.post_process_masks(UpperCamelCase__, np.array(UpperCamelCase__ ), np.array(UpperCamelCase__ ) ) @require_vision @require_tf class A ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = tempfile.mkdtemp() lowerCAmelCase_ = SamImageProcessor() lowerCAmelCase_ = SamProcessor(UpperCamelCase__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self, **UpperCamelCase__ ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **UpperCamelCase__ ).image_processor def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] lowerCAmelCase_ = [Image.fromarray(np.moveaxis(UpperCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase_ = self.get_image_processor(do_normalize=UpperCamelCase__, padding_value=1.0 ) lowerCAmelCase_ = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=UpperCamelCase__, padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = self.prepare_image_inputs() lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''np''' ) lowerCAmelCase_ = processor(images=UpperCamelCase__, return_tensors='''np''' ) input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('''reshaped_input_sizes''' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2 ) @require_tf def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = [tf.ones((1, 3, 5, 5) )] lowerCAmelCase_ = [[1764, 2646]] lowerCAmelCase_ = [[683, 1024]] lowerCAmelCase_ = processor.post_process_masks(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, return_tensors='''tf''' ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, tf.convert_to_tensor(UpperCamelCase__ ), tf.convert_to_tensor(UpperCamelCase__ ), return_tensors='''tf''', ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) # should also work with np lowerCAmelCase_ = [np.ones((1, 3, 5, 5) )] lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, np.array(UpperCamelCase__ ), np.array(UpperCamelCase__ ), return_tensors='''tf''' ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646) ) lowerCAmelCase_ = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, np.array(UpperCamelCase__ ), np.array(UpperCamelCase__ ), return_tensors='''tf''' ) @require_vision @require_torchvision class A ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = tempfile.mkdtemp() lowerCAmelCase_ = SamImageProcessor() lowerCAmelCase_ = SamProcessor(UpperCamelCase__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self, **UpperCamelCase__ ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname, **UpperCamelCase__ ).image_processor def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] lowerCAmelCase_ = [Image.fromarray(np.moveaxis(UpperCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = np.random.randint(0, 2, size=(1, 3, 5, 5) ).astype(np.floataa ) lowerCAmelCase_ = [tf.convert_to_tensor(UpperCamelCase__ )] lowerCAmelCase_ = [torch.tensor(UpperCamelCase__ )] lowerCAmelCase_ = [[1764, 2646]] lowerCAmelCase_ = [[683, 1024]] lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, return_tensors='''tf''' ) lowerCAmelCase_ = processor.post_process_masks( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, return_tensors='''pt''' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.get_image_processor() lowerCAmelCase_ = SamProcessor(image_processor=UpperCamelCase__ ) lowerCAmelCase_ = self.prepare_image_inputs() lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''pt''' )['''pixel_values'''].numpy() lowerCAmelCase_ = processor(images=UpperCamelCase__, return_tensors='''pt''' )['''pixel_values'''].numpy() lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''tf''' )['''pixel_values'''].numpy() lowerCAmelCase_ = processor(images=UpperCamelCase__, return_tensors='''tf''' )['''pixel_values'''].numpy() self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__ ) ) self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__ ) ) self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__ ) )
278
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def __UpperCamelCase ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCAmelCase_ = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowerCAmelCase_ = features.copy() if features else default_expected_features lowerCAmelCase_ = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase_ = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} lowerCAmelCase_ = features.copy() if features else default_expected_features lowerCAmelCase_ = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase_ = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def __UpperCamelCase ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} lowerCAmelCase_ = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} lowerCAmelCase_ = features.copy() lowerCAmelCase_ = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowerCAmelCase_ = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def __UpperCamelCase ( _A , _A , _A ): if issubclass(_A , _A ): lowerCAmelCase_ = jsonl_path elif issubclass(_A , _A ): lowerCAmelCase_ = [jsonl_path] lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowerCAmelCase_ = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def __UpperCamelCase ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: lowerCAmelCase_ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCAmelCase_ = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowerCAmelCase_ = features.copy() if features else default_expected_features lowerCAmelCase_ = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase_ = JsonDatasetReader({'''train''': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def __UpperCamelCase ( _A , _A , _A ): if split: lowerCAmelCase_ = {split: jsonl_path} else: lowerCAmelCase_ = '''train''' lowerCAmelCase_ = {'''train''': jsonl_path, '''test''': jsonl_path} lowerCAmelCase_ = tmp_path / '''cache''' lowerCAmelCase_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowerCAmelCase_ = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def __UpperCamelCase ( _A ): return json.load(_A ) def __UpperCamelCase ( _A ): return [json.loads(_A ) for line in buffer] class A : @pytest.mark.parametrize('''lines, load_json_function''', [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, lines=UpperCamelCase__ ).write() buffer.seek(0 ) lowerCAmelCase_ = load_json_function(UpperCamelCase__ ) assert isinstance(UpperCamelCase__, UpperCamelCase__ ) assert isinstance(exported_content[0], UpperCamelCase__ ) assert len(UpperCamelCase__ ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''', [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ], ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, lines=UpperCamelCase__, orient=UpperCamelCase__ ).write() buffer.seek(0 ) lowerCAmelCase_ = load_json(UpperCamelCase__ ) assert isinstance(UpperCamelCase__, UpperCamelCase__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase__, '''keys''' ) and not hasattr(exported_content[0], '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase__ ) == 10 @pytest.mark.parametrize('''lines, load_json_function''', [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, lines=UpperCamelCase__, num_proc=2 ).write() buffer.seek(0 ) lowerCAmelCase_ = load_json_function(UpperCamelCase__ ) assert isinstance(UpperCamelCase__, UpperCamelCase__ ) assert isinstance(exported_content[0], UpperCamelCase__ ) assert len(UpperCamelCase__ ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''', [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ], ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, lines=UpperCamelCase__, orient=UpperCamelCase__, num_proc=2 ).write() buffer.seek(0 ) lowerCAmelCase_ = load_json(UpperCamelCase__ ) assert isinstance(UpperCamelCase__, UpperCamelCase__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase__, '''keys''' ) and not hasattr(exported_content[0], '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase__ ) == 10 def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ): """simple docstring""" with pytest.raises(UpperCamelCase__ ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, num_proc=0 ) @pytest.mark.parametrize('''compression, extension''', [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = tmp_path_factory.mktemp('''data''' ) / f"test.json.{extension}" lowerCAmelCase_ = str(shared_datadir / f"test_file.json.{extension}" ) JsonDatasetWriter(UpperCamelCase__, UpperCamelCase__, compression=UpperCamelCase__ ).write() with fsspec.open(UpperCamelCase__, '''rb''', compression='''infer''' ) as f: lowerCAmelCase_ = f.read() with fsspec.open(UpperCamelCase__, '''rb''', compression='''infer''' ) as f: lowerCAmelCase_ = f.read() assert exported_content == original_content
278
1
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 PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowercase: Optional[Any] = logging.get_logger(__name__) def a( A : Optional[Any] , A : List[str] , A : str , A : str ) -> Optional[Any]: """simple docstring""" a = original_name.split("." )[0] a = key.split("." ) a = int(key_list[key_list.index(A ) - 2] ) a = int(key_list[key_list.index(A ) - 1] ) a = orig_block_num - offset a = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def a( A : int ) -> Dict: """simple docstring""" a = OrderedDict() a , a = 0, 0 for key, value in state_dict.items(): if key.startswith("network" ): a = key.replace("network" , "poolformer.encoder" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("bias" ) and "patch_embed" not in key: patch_emb_offset += 1 a = key[: key.find("proj" )] a = key.replace(A , f'''patch_embeddings.{total_embed_found}.''' ) a = key.replace("proj" , "projection" ) if key.endswith("bias" ): total_embed_found += 1 if "patch_embeddings" in key: a = "poolformer.encoder." + key if "mlp.fc1" in key: a = replace_key_with_offset(A , A , "mlp.fc1" , "output.conv1" ) if "mlp.fc2" in key: a = replace_key_with_offset(A , A , "mlp.fc2" , "output.conv2" ) if "norm1" in key: a = replace_key_with_offset(A , A , "norm1" , "before_norm" ) if "norm2" in key: a = replace_key_with_offset(A , A , "norm2" , "after_norm" ) if "layer_scale_1" in key: a = replace_key_with_offset(A , A , "layer_scale_1" , "layer_scale_1" ) if "layer_scale_2" in key: a = replace_key_with_offset(A , A , "layer_scale_2" , "layer_scale_2" ) if "head" in key: a = key.replace("head" , "classifier" ) a = value return new_state_dict def a( ) -> Dict: """simple docstring""" a = "http://images.cocodataset.org/val2017/000000039769.jpg" a = Image.open(requests.get(A , stream=A ).raw ) return image @torch.no_grad() def a( A : List[Any] , A : List[str] , A : str ) -> Optional[int]: """simple docstring""" a = PoolFormerConfig() # set attributes based on model_name a = "huggingface/label-files" a = model_name[-3:] a = 1000 a = "imagenet-1k-id2label.json" a = (1, 1000) # set config attributes a = json.load(open(hf_hub_download(A , A , repo_type="dataset" ) , "r" ) ) a = {int(A ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} if size == "s12": a = [2, 2, 6, 2] a = [64, 128, 320, 512] a = 4.0 a = 0.9 elif size == "s24": a = [4, 4, 12, 4] a = [64, 128, 320, 512] a = 4.0 a = 0.9 elif size == "s36": a = [6, 6, 18, 6] a = [64, 128, 320, 512] a = 4.0 a = 1e-6 a = 0.9 elif size == "m36": a = [6, 6, 18, 6] a = [96, 192, 384, 768] a = 4.0 a = 1e-6 a = 0.95 elif size == "m48": a = [8, 8, 24, 8] a = [96, 192, 384, 768] a = 4.0 a = 1e-6 a = 0.95 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor a = PoolFormerImageProcessor(crop_pct=A ) # Prepare image a = prepare_img() a = image_processor(images=A , return_tensors="pt" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict a = torch.load(A , map_location=torch.device("cpu" ) ) # rename keys a = rename_keys(A ) # create HuggingFace model and load state dict a = PoolFormerForImageClassification(A ) model.load_state_dict(A ) model.eval() # Define image processor a = PoolFormerImageProcessor(crop_pct=A ) a = image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values # forward pass a = model(A ) a = outputs.logits # define expected logit slices for different models if size == "s12": a = torch.tensor([-0.3_045, -0.6_758, -0.4_869] ) elif size == "s24": a = torch.tensor([0.4_402, -0.1_374, -0.8_045] ) elif size == "s36": a = torch.tensor([-0.6_080, -0.5_133, -0.5_898] ) elif size == "m36": a = torch.tensor([0.3_952, 0.2_263, -1.2_668] ) elif size == "m48": a = torch.tensor([0.1_167, -0.0_656, -0.3_423] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , A , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A ) if __name__ == "__main__": _lowercase: Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model_name", default="poolformer_s12", 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." ) _lowercase: Union[str, Any] = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
365
def a( A : int , A : float , A : float ) -> float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (volume) ) ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (pressure) ) ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((pressure * volume) / (0.0_821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
71
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __lowerCAmelCase ( UpperCAmelCase__ ): def UpperCamelCase ( self : Optional[Any] ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCamelCase ( self : Dict ): """simple docstring""" with self.assertRaises(snake_case__ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCamelCase ( self : int ): """simple docstring""" with self.assertRaises(snake_case__ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCamelCase ( self : Tuple ): """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def UpperCamelCase ( self : int ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCamelCase ( self : Dict ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCamelCase ( self : Optional[Any] ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def UpperCamelCase ( self : str ): """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def UpperCamelCase ( self : str ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def UpperCamelCase ( self : Optional[int] ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCamelCase ( self : Any ): """simple docstring""" import PIL.Image _UpperCAmelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=snake_case__ ) as mock_cast_to_python_objects: _UpperCAmelCase = pa.array(TypedSequence([{"path": None, "bytes": b"image_bytes"}, pil_image] , type=Image() ) ) _UpperCAmelCase , _UpperCAmelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , snake_case__ ) self.assertFalse(kwargs["optimize_list_casting"] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferReader(snake_case_ ) if isinstance(snake_case_ , pa.Buffer ) else pa.memory_map(snake_case_ ) _UpperCAmelCase = pa.ipc.open_stream(snake_case_ ) _UpperCAmelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ , schema=snake_case_ , writer_batch_size=snake_case_ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=snake_case_ , features=snake_case_ ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pa.ipc.open_stream(snake_case_ ) _UpperCAmelCase = f.read_all() _UpperCAmelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(snake_case_ ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) def __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ , writer_batch_size=snake_case_ , hash_salt="split_name" , check_duplicates=snake_case_ , ) as writer: with pytest.raises(snake_case_ ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ , writer_batch_size=snake_case_ , hash_salt="split_name" , check_duplicates=snake_case_ , ) as writer: with pytest.raises(snake_case_ ): writer.write({"col_1": "foo", "col_2": 1} , key=10 ) writer.write({"col_1": "bar", "col_2": 2} , key=10 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ , writer_batch_size=snake_case_ , hash_salt="split_name" , check_duplicates=snake_case_ , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ , schema=snake_case_ , writer_batch_size=snake_case_ ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ , schema=snake_case_ , writer_batch_size=snake_case_ ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ , schema=snake_case_ , writer_batch_size=snake_case_ ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __SCREAMING_SNAKE_CASE ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} _UpperCAmelCase = os.path.join(snake_case_ , "test.arrow" ) with ArrowWriter(path=snake_case_ , schema=pa.schema(snake_case_ ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(snake_case_ , metadata=writer._schema.metadata ) _check_output(snake_case_ , 1 ) def __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' if pa.types.is_list(snake_case_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' if isinstance(lst[0] , snake_case_ ): change_first_primitive_element_in_list(lst[0] , snake_case_ ) else: _UpperCAmelCase = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.array(TypedSequence(snake_case_ , optimized_int_type=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = pa.array(OptimizedTypedSequence(snake_case_ , col=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCAmelCase = copy.deepcopy(snake_case_ ) _UpperCAmelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(snake_case_ , snake_case_ ) _UpperCAmelCase = pa.array(OptimizedTypedSequence(snake_case_ , col=snake_case_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' _UpperCAmelCase = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=snake_case_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' _UpperCAmelCase = "mock://dataset-train.arrow" with ArrowWriter(path=snake_case_ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(snake_case_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(snake_case_ ) def __SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter(stream=snake_case_ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(snake_case_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): '''simple docstring''' import PIL.Image _UpperCAmelCase = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(snake_case_ , format="png" ) _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter( stream=snake_case_ , features=Features({"image": Image()} ) , embed_local_files=snake_case_ ) as writer: writer.write({"image": image_path} ) writer.finalize() _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(snake_case_ ) _UpperCAmelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , snake_case_ ) with open(snake_case_ , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _UpperCAmelCase = pa.schema([pa.field("col_1" , pa.string() , nullable=snake_case_ )] ) _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter(stream=snake_case_ ) as writer: writer._build_writer(inferred_schema=snake_case_ ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
133
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ : Dict = logging.get_logger(__name__) lowercase_ : Union[str, Any] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class __lowerCAmelCase ( UpperCAmelCase__ ): snake_case_ : int = "ctrl" snake_case_ : Optional[int] = ["past_key_values"] snake_case_ : Tuple = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , snake_case__ : List[str]=246_534 , snake_case__ : Optional[Any]=256 , snake_case__ : List[str]=1_280 , snake_case__ : Optional[int]=8_192 , snake_case__ : List[Any]=48 , snake_case__ : Dict=16 , snake_case__ : int=0.1 , snake_case__ : List[str]=0.1 , snake_case__ : Optional[int]=1e-6 , snake_case__ : Dict=0.02 , snake_case__ : List[Any]=True , **snake_case__ : List[str] , ): """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**snake_case__ )
133
1
from math import factorial snake_case__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def _a ( lowerCamelCase: int ) -> int: '''simple docstring''' if not isinstance(lowerCamelCase , lowerCamelCase ): 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(lowerCamelCase ) ) def _a ( lowerCamelCase: int = 60 , lowerCamelCase: int = 1_00_00_00 ) -> int: '''simple docstring''' if not isinstance(lowerCamelCase , lowerCamelCase ) or not isinstance(lowerCamelCase , lowerCamelCase ): 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 __A = 0 # the cached sizes of the previous chains __A = {} for start_chain_element in range(1 , lowerCamelCase ): # The temporary set will contain the elements of the chain __A = set() __A = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __A = 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(lowerCamelCase ) chain_set_length += 1 __A = digit_factorial_sum(lowerCamelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __A = 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()}')
250
import sys def _a ( lowerCamelCase: Tuple ) -> Tuple: '''simple docstring''' __A = len(lowerCamelCase ) __A = [[0 for x in range(lowerCamelCase )] for x in range(lowerCamelCase )] __A = [[0 for x in range(lowerCamelCase )] for x in range(lowerCamelCase )] for chain_length in range(2 , lowerCamelCase ): for a in range(1 , n - chain_length + 1 ): __A = a + chain_length - 1 __A = sys.maxsize for c in range(lowerCamelCase , lowerCamelCase ): __A = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: __A = cost __A = c return matrix, sol def _a ( lowerCamelCase: Optional[int] , lowerCamelCase: Optional[Any] , lowerCamelCase: List[str] ) -> Tuple: '''simple docstring''' if i == j: print('''A''' + str(lowerCamelCase ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(lowerCamelCase , lowerCamelCase , optimal_solution[i][j] ) print_optiomal_solution(lowerCamelCase , optimal_solution[i][j] + 1 , lowerCamelCase ) print(''')''' , end=''' ''' ) def _a ( ) -> List[str]: '''simple docstring''' __A = [30, 35, 15, 5, 10, 20, 25] __A = len(lowerCamelCase ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 __A , __A = matrix_chain_order(lowerCamelCase ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(lowerCamelCase , 1 , n - 1 ) if __name__ == "__main__": main()
250
1
from ..utils import DummyObject, requires_backends class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: int , *UpperCamelCase_: List[str] , **UpperCamelCase_: Optional[Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: str , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: str , *UpperCamelCase_: Optional[int] , **UpperCamelCase_: List[str] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = ['sentencepiece'] def __init__( self: List[str] , *UpperCamelCase_: Dict , **UpperCamelCase_: Optional[Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : List[Any] = ['sentencepiece'] def __init__( self: Optional[Any] , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Optional[int] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Dict = ['sentencepiece'] def __init__( self: Any , *UpperCamelCase_: Union[str, Any] , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = ['sentencepiece'] def __init__( self: Any , *UpperCamelCase_: int , **UpperCamelCase_: Optional[int] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: Optional[int] , *UpperCamelCase_: Any , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: Dict , *UpperCamelCase_: Dict , **UpperCamelCase_: Optional[Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[Any] = ['sentencepiece'] def __init__( self: Optional[Any] , *UpperCamelCase_: Tuple , **UpperCamelCase_: List[Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Dict = ['sentencepiece'] def __init__( self: List[str] , *UpperCamelCase_: int , **UpperCamelCase_: Dict ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Any = ['sentencepiece'] def __init__( self: Dict , *UpperCamelCase_: int , **UpperCamelCase_: Any ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = ['sentencepiece'] def __init__( self: int , *UpperCamelCase_: Any , **UpperCamelCase_: Optional[int] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: int , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Optional[int] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: Optional[Any] , *UpperCamelCase_: Any , **UpperCamelCase_: Union[str, Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Any = ['sentencepiece'] def __init__( self: Optional[Any] , *UpperCamelCase_: Dict , **UpperCamelCase_: List[str] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : str = ['sentencepiece'] def __init__( self: Tuple , *UpperCamelCase_: Union[str, Any] , **UpperCamelCase_: List[str] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[Any] = ['sentencepiece'] def __init__( self: List[str] , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: str , *UpperCamelCase_: Any , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: List[str] , *UpperCamelCase_: int , **UpperCamelCase_: Dict ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: List[Any] , *UpperCamelCase_: List[Any] , **UpperCamelCase_: Any ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Any = ['sentencepiece'] def __init__( self: Dict , *UpperCamelCase_: Optional[int] , **UpperCamelCase_: Union[str, Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Any = ['sentencepiece'] def __init__( self: Optional[int] , *UpperCamelCase_: List[Any] , **UpperCamelCase_: Tuple ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : List[Any] = ['sentencepiece'] def __init__( self: str , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Optional[int] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : int = ['sentencepiece'] def __init__( self: Union[str, Any] , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Any ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : str = ['sentencepiece'] def __init__( self: Union[str, Any] , *UpperCamelCase_: List[str] , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : int = ['sentencepiece'] def __init__( self: Optional[int] , *UpperCamelCase_: Tuple , **UpperCamelCase_: str ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : int = ['sentencepiece'] def __init__( self: Dict , *UpperCamelCase_: Optional[int] , **UpperCamelCase_: List[Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Tuple = ['sentencepiece'] def __init__( self: Dict , *UpperCamelCase_: int , **UpperCamelCase_: int ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : Optional[int] = ['sentencepiece'] def __init__( self: List[str] , *UpperCamelCase_: Union[str, Any] , **UpperCamelCase_: Union[str, Any] ): requires_backends(self , ["""sentencepiece"""] ) class lowerCamelCase__( metaclass=__lowerCamelCase): UpperCAmelCase__ : int = ['sentencepiece'] def __init__( self: Optional[Any] , *UpperCamelCase_: List[str] , **UpperCamelCase_: int ): requires_backends(self , ["""sentencepiece"""] )
12
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig 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 TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A_ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : int=3 , lowercase_ : Dict=32 , lowercase_ : Optional[Any]=3 , lowercase_ : Tuple=10 , lowercase_ : Optional[Any]=[10, 20, 30, 40] , lowercase_ : List[str]=[1, 1, 2, 1] , lowercase_ : Optional[int]=True , lowercase_ : str=True , lowercase_ : Dict="relu" , lowercase_ : Optional[Any]=3 , lowercase_ : List[str]=None , ) -> int: UpperCAmelCase : Dict = parent UpperCAmelCase : Dict = batch_size UpperCAmelCase : Any = image_size UpperCAmelCase : Any = num_channels UpperCAmelCase : List[str] = embeddings_size UpperCAmelCase : str = hidden_sizes UpperCAmelCase : str = depths UpperCAmelCase : Optional[int] = is_training UpperCAmelCase : int = use_labels UpperCAmelCase : Optional[int] = hidden_act UpperCAmelCase : List[Any] = num_labels UpperCAmelCase : Union[str, Any] = scope UpperCAmelCase : Any = len(lowercase_ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase : Any = None if self.use_labels: UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: return ResNetConfig( 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 , image_size=self.image_size , ) def UpperCAmelCase_ ( self : int , lowercase_ : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] ) -> Union[str, Any]: UpperCAmelCase : List[Any] = TFResNetModel(config=lowercase_ ) UpperCAmelCase : int = model(lowercase_ ) # 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 UpperCAmelCase_ ( self : Any , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Optional[int] ) -> List[Any]: UpperCAmelCase : List[Any] = self.num_labels UpperCAmelCase : Union[str, Any] = TFResNetForImageClassification(lowercase_ ) UpperCAmelCase : Any = model(lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[Any] = config_and_inputs UpperCAmelCase : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( _snake_case , _snake_case , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () UpperCAmelCase_ : Dict = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : List[Any] = False UpperCAmelCase_ : str = False UpperCAmelCase_ : Optional[int] = False def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: UpperCAmelCase : Optional[int] = TFResNetModelTester(self ) UpperCAmelCase : Dict = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ ) def UpperCAmelCase_ ( self : str ) -> Any: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: return @unittest.skip(reason='ResNet does not use inputs_embeds' ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: pass @unittest.skip(reason='ResNet does not support input and output embeddings' ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: pass def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: UpperCAmelCase , UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase : List[Any] = model_class(lowercase_ ) UpperCAmelCase : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase : str = [*signature.parameters.keys()] UpperCAmelCase : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: def check_hidden_states_output(lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): UpperCAmelCase : Union[str, Any] = model_class(lowercase_ ) UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(lowercase_ , lowercase_ ) ) UpperCAmelCase : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase : int = self.model_tester.num_stages self.assertEqual(len(lowercase_ ) , expected_num_stages + 1 ) # ResNet'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 // 4, self.model_tester.image_size // 4] , ) UpperCAmelCase , UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase : Tuple = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCAmelCase : List[Any] = layer_type UpperCAmelCase : int = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase : List[Any] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase : str = TFResNetModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def UpperCamelCase( ): UpperCAmelCase : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Any: UpperCAmelCase : Optional[int] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCAmelCase : Any = self.default_image_processor UpperCAmelCase : List[Any] = prepare_img() UpperCAmelCase : Dict = image_processor(images=lowercase_ , return_tensors='tf' ) # forward pass UpperCAmelCase : List[Any] = model(**lowercase_ ) # verify the logits UpperCAmelCase : Optional[Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) UpperCAmelCase : int = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowercase_ , atol=1E-4 ) )
151
0
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging lowerCAmelCase : Any = logging.get_logger(__name__) lowerCAmelCase : List[Any] = {"vocab_file": "spiece.model"} lowerCAmelCase : List[str] = { "vocab_file": { "TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model", } } class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , _a , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , _a = None , **_a , ): """simple docstring""" lowerCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token lowerCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=lowerCamelCase_ , remove_space=lowerCamelCase_ , keep_accents=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , additional_special_tokens=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) lowerCamelCase = 3 lowerCamelCase = do_lower_case lowerCamelCase = remove_space lowerCamelCase = keep_accents lowerCamelCase = vocab_file lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCamelCase_ ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """ """See https://pypi.org/project/jieba/ for installation.""" ) lowerCamelCase = jieba lowerCamelCase = str.maketrans(""" \n""" , """\u2582\u2583""" ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def _lowerCAmelCase ( self ): """simple docstring""" return len(self.sp_model ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowerCamelCase = self.__dict__.copy() lowerCamelCase = None return state def __setstate__( self , _a ): """simple docstring""" lowerCamelCase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase = {} lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCAmelCase ( self , _a ): """simple docstring""" if self.remove_space: lowerCamelCase = """ """.join(inputs.strip().split() ) else: lowerCamelCase = inputs lowerCamelCase = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: lowerCamelCase = unicodedata.normalize("""NFKD""" , lowerCamelCase_ ) lowerCamelCase = """""".join([c for c in outputs if not unicodedata.combining(lowerCamelCase_ )] ) if self.do_lower_case: lowerCamelCase = outputs.lower() return outputs def _lowerCAmelCase ( self , _a ): """simple docstring""" lowerCamelCase = self.preprocess_text(lowerCamelCase_ ) lowerCamelCase = self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) lowerCamelCase = [] for piece in pieces: if len(lowerCamelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowerCamelCase = self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCamelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase = cur_pieces[1:] else: lowerCamelCase = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(lowerCamelCase_ ) else: new_pieces.append(lowerCamelCase_ ) return new_pieces def _lowerCAmelCase ( self , _a ): """simple docstring""" return self.sp_model.PieceToId(lowerCamelCase_ ) def _lowerCAmelCase ( self , _a ): """simple docstring""" return self.sp_model.IdToPiece(lowerCamelCase_ ) def _lowerCAmelCase ( self , _a ): """simple docstring""" lowerCamelCase = """""".join(lowerCamelCase_ ).replace(lowerCamelCase_ , """ """ ).strip() return out_string def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = [self.sep_token_id] lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowerCAmelCase ( self , _a , _a = None , _a = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is not None: return ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] return ([0] * len(lowerCamelCase_ )) + [1, 1] def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = [self.sep_token_id] lowerCamelCase = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" if not os.path.isdir(lowerCamelCase_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCamelCase = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: lowerCamelCase = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,) def _lowerCAmelCase ( self , *_a , **_a ): """simple docstring""" lowerCamelCase = super()._decode(*lowerCamelCase_ , **lowerCamelCase_ ) lowerCamelCase = text.replace(""" """ , """""" ).replace("""\u2582""" , """ """ ).replace("""\u2583""" , """\n""" ) return text
355
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __magic_name__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = 0 def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase = Path(_a ) / """preprocessor_config.json""" lowerCamelCase = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase = Path(_a ) / """preprocessor_config.json""" lowerCamelCase = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase = CLIPConfig() # Create a dummy config file with image_proceesor_type lowerCamelCase = Path(_a ) / """preprocessor_config.json""" lowerCamelCase = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally lowerCamelCase = AutoImageProcessor.from_pretrained(_a ).to_dict() config_dict.pop("""image_processor_type""" ) lowerCamelCase = CLIPImageProcessor(**_a ) # save in new folder model_config.save_pretrained(_a ) config.save_pretrained(_a ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a ) # make sure private variable is not incorrectly saved lowerCamelCase = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase = Path(_a ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" with self.assertRaisesRegex( _a , """clip-base is not a local folder and is not a valid model identifier""" ): lowerCamelCase = AutoImageProcessor.from_pretrained("""clip-base""" ) def _lowerCAmelCase ( self ): """simple docstring""" with self.assertRaisesRegex( _a , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): lowerCamelCase = AutoImageProcessor.from_pretrained(_a , revision="""aaaaaa""" ) def _lowerCAmelCase ( self ): """simple docstring""" with self.assertRaisesRegex( _a , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): lowerCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def _lowerCAmelCase ( self ): """simple docstring""" # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_a ): lowerCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): lowerCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) lowerCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a , trust_remote_code=_a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def _lowerCAmelCase ( self ): """simple docstring""" try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoImageProcessor.register(_a , _a ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase = Path(_a ) / """preprocessor_config.json""" lowerCamelCase = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) lowerCamelCase = CustomImageProcessor.from_pretrained(_a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) lowerCamelCase = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowerCAmelCase ( self ): """simple docstring""" class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = True try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # If remote code is not set, the default is to use local lowerCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. lowerCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub lowerCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(_a , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
168
0
import inspect import unittest class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : Optional[int] ): """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def __magic_name__ ( self : Optional[Any] ): """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps _A: Optional[Any] = inspect.getmembers(lowerCAmelCase_ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": _A: Any = '''k-diffusion''' elif backend == "invisible_watermark": _A: Any = '''invisible-watermark''' assert backend in deps, F"""{backend} is not in the deps table!"""
121
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : List[str] = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json', 'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json', 'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json', 'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json', 'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json', 'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json', 'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json', 'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json', 'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json', 'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json', } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : int = '''xlm''' __UpperCamelCase : Optional[Any] = { '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self : List[Any] , lowerCAmelCase_ : Dict=3_0_1_4_5 , lowerCAmelCase_ : Union[str, Any]=2_0_4_8 , lowerCAmelCase_ : List[str]=1_2 , lowerCAmelCase_ : Optional[Any]=1_6 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : List[str]=False , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : List[str]=False , lowerCAmelCase_ : Optional[Any]=1 , lowerCAmelCase_ : List[str]=True , lowerCAmelCase_ : Tuple=5_1_2 , lowerCAmelCase_ : Tuple=2_0_4_8**-0.5 , lowerCAmelCase_ : List[str]=1e-12 , lowerCAmelCase_ : Any=0.02 , lowerCAmelCase_ : int=0 , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : Dict=2 , lowerCAmelCase_ : List[Any]=3 , lowerCAmelCase_ : int=5 , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : Union[str, Any]="first" , lowerCAmelCase_ : int=True , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Any=True , lowerCAmelCase_ : int=0.1 , lowerCAmelCase_ : Tuple=5 , lowerCAmelCase_ : Tuple=5 , lowerCAmelCase_ : Optional[int]=0 , lowerCAmelCase_ : Optional[Any]=0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Dict=0 , **lowerCAmelCase_ : List[Any] , ): """simple docstring""" _A: Dict = vocab_size _A: Dict = emb_dim _A: Optional[Any] = n_layers _A: str = n_heads _A: Optional[int] = dropout _A: Union[str, Any] = attention_dropout _A: Any = gelu_activation _A: Optional[Any] = sinusoidal_embeddings _A: Any = causal _A: Optional[int] = asm _A: List[str] = n_langs _A: int = use_lang_emb _A: Any = layer_norm_eps _A: Tuple = bos_index _A: Any = eos_index _A: List[str] = pad_index _A: str = unk_index _A: str = mask_index _A: List[Any] = is_encoder _A: List[Any] = max_position_embeddings _A: str = embed_init_std _A: int = init_std _A: List[str] = summary_type _A: List[str] = summary_use_proj _A: Tuple = summary_activation _A: Dict = summary_proj_to_labels _A: Tuple = summary_first_dropout _A: str = start_n_top _A: str = end_n_top _A: Optional[Any] = mask_token_id _A: Any = lang_id if "n_words" in kwargs: _A: Union[str, Any] = kwargs['''n_words'''] super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property def __magic_name__ ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _A: int = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _A: Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
121
1
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean _UpperCAmelCase = 0 _UpperCAmelCase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _UpperCAmelCase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right _UpperCAmelCase = tuple[int, int] class _UpperCamelCase : def __init__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Node | None , ) -> None: """simple docstring""" UpperCamelCase_ = pos_x UpperCamelCase_ = pos_y UpperCamelCase_ = (pos_y, pos_x) UpperCamelCase_ = goal_x UpperCamelCase_ = goal_y UpperCamelCase_ = g_cost UpperCamelCase_ = parent UpperCamelCase_ = self.calculate_heuristic() UpperCamelCase_ = self.g_cost + self.h_cost def lowercase ( self: List[Any] ) -> float: """simple docstring""" UpperCamelCase_ = self.pos_x - self.goal_x UpperCamelCase_ = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(_SCREAMING_SNAKE_CASE ) + abs(_SCREAMING_SNAKE_CASE ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self: List[Any] , _SCREAMING_SNAKE_CASE: Node ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class _UpperCamelCase : def __init__( self: Dict , _SCREAMING_SNAKE_CASE: TPosition , _SCREAMING_SNAKE_CASE: TPosition ) -> Any: """simple docstring""" UpperCamelCase_ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [self.start] UpperCamelCase_ = [] UpperCamelCase_ = False def lowercase ( self: Union[str, Any] ) -> list[TPosition]: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCamelCase_ = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path UpperCamelCase_ = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) return [self.start.pos] def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node ) -> list[Node]: """simple docstring""" UpperCamelCase_ = [] for action in delta: UpperCamelCase_ = parent.pos_x + action[1] UpperCamelCase_ = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node | None ) -> list[TPosition]: """simple docstring""" UpperCamelCase_ = node UpperCamelCase_ = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCamelCase_ = current_node.parent path.reverse() return path class _UpperCamelCase : def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: TPosition , _SCREAMING_SNAKE_CASE: TPosition ) -> None: """simple docstring""" UpperCamelCase_ = AStar(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = AStar(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = False def lowercase ( self: int ) -> list[TPosition]: """simple docstring""" while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() UpperCamelCase_ = self.fwd_astar.open_nodes.pop(0 ) UpperCamelCase_ = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.fwd_astar.closed_nodes.append(_SCREAMING_SNAKE_CASE ) self.bwd_astar.closed_nodes.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = current_bwd_node UpperCamelCase_ = current_fwd_node UpperCamelCase_ = { self.fwd_astar: self.fwd_astar.get_successors(_SCREAMING_SNAKE_CASE ), self.bwd_astar: self.bwd_astar.get_successors(_SCREAMING_SNAKE_CASE ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path UpperCamelCase_ = astar.open_nodes.pop( astar.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) return [self.fwd_astar.start.pos] def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node , _SCREAMING_SNAKE_CASE: Node ) -> list[TPosition]: """simple docstring""" UpperCamelCase_ = self.fwd_astar.retrace_path(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.bwd_astar.retrace_path(_SCREAMING_SNAKE_CASE ) bwd_path.pop() bwd_path.reverse() UpperCamelCase_ = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] _UpperCAmelCase = (0, 0) _UpperCAmelCase = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _UpperCAmelCase = time.time() _UpperCAmelCase = AStar(init, goal) _UpperCAmelCase = a_star.search() _UpperCAmelCase = time.time() - start_time print(f'''AStar execution time = {end_time:f} seconds''') _UpperCAmelCase = time.time() _UpperCAmelCase = BidirectionalAStar(init, goal) _UpperCAmelCase = time.time() - bd_start_time print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
352
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _UpperCamelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _UpperCamelCase : Optional[int] = field( default=1_0_2_4 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Source language id for translation.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Target language id for translation.'''} ) _UpperCamelCase : Optional[int] = field(default=lowerCAmelCase_ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _UpperCamelCase : bool = field( default=lowerCAmelCase_ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(UpperCamelCase_ , os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) ) def lowerCAmelCase_ ( ) -> Optional[int]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() check_output_dir(UpperCamelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert hasattr(UpperCamelCase_ , UpperCamelCase_ ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCamelCase_ , UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCamelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCamelCase_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCamelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCamelCase_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCamelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCamelCase_ = SeqaSeqDataset # Get datasets UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCamelCase_ = ( build_compute_metrics_fn(data_args.task , UpperCamelCase_ ) if training_args.predict_with_generate else None ) UpperCamelCase_ = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , data_args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , data_collator=SeqaSeqDataCollator( UpperCamelCase_ , UpperCamelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) UpperCamelCase_ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) UpperCamelCase_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCamelCase_ = train_result.metrics UpperCamelCase_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) UpperCamelCase_ = trainer.evaluate(metric_key_prefix="val" ) UpperCamelCase_ = data_args.n_val UpperCamelCase_ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) UpperCamelCase_ = trainer.predict(test_dataset=UpperCamelCase_ , metric_key_prefix="test" ) UpperCamelCase_ = test_output.metrics UpperCamelCase_ = data_args.n_test if trainer.is_world_process_zero(): UpperCamelCase_ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.predict_with_generate: UpperCamelCase_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) UpperCamelCase_ = lmap(str.strip , UpperCamelCase_ ) write_txt_file(UpperCamelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(UpperCamelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
328
0
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase_ = False class __A ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : Dict=32 ) -> Union[str, Any]: """simple docstring""" set_seed(0 ) lowercase__ : Union[str, Any] = UNetaDModel(sample_size=_snake_case ,in_channels=3 ,out_channels=3 ) lowercase__ : Optional[int] = torch.optim.SGD(model.parameters() ,lr=0.0001 ) return model, optimizer @slow def UpperCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" lowercase__ : Tuple = 'cpu' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowercase__ : Any = DDPMScheduler( num_train_timesteps=1_000 ,beta_start=0.0001 ,beta_end=0.02 ,beta_schedule='''linear''' ,clip_sample=_snake_case ,) lowercase__ : Union[str, Any] = DDIMScheduler( num_train_timesteps=1_000 ,beta_start=0.0001 ,beta_end=0.02 ,beta_schedule='''linear''' ,clip_sample=_snake_case ,) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowercase__ : Optional[int] = [torch.randn((4, 3, 32, 32) ).clip(-1 ,1 ).to(_snake_case ) for _ in range(4 )] lowercase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(_snake_case ) for _ in range(4 )] lowercase__ : Optional[int] = [torch.randint(0 ,1_000 ,(4,) ).long().to(_snake_case ) for _ in range(4 )] # train with a DDPM scheduler lowercase__ : Optional[int] = self.get_model_optimizer(resolution=32 ) model.train().to(_snake_case ) for i in range(4 ): optimizer.zero_grad() lowercase__ : Optional[Any] = ddpm_scheduler.add_noise(clean_images[i] ,noise[i] ,timesteps[i] ) lowercase__ : List[Any] = model(_snake_case ,timesteps[i] ).sample lowercase__ : str = torch.nn.functional.mse_loss(_snake_case ,noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowercase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(_snake_case ) for i in range(4 ): optimizer.zero_grad() lowercase__ : Dict = ddim_scheduler.add_noise(clean_images[i] ,noise[i] ,timesteps[i] ) lowercase__ : Optional[Any] = model(_snake_case ,timesteps[i] ).sample lowercase__ : Optional[int] = torch.nn.functional.mse_loss(_snake_case ,noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(_snake_case ,_snake_case ,atol=1e-5 ) ) self.assertTrue(torch.allclose(_snake_case ,_snake_case ,atol=1e-5 ) )
16
import math def snake_case__ ( SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' lowercase__ : Optional[Any] = [] lowercase__ : str = 2 lowercase__ : Optional[Any] = int(math.sqrt(SCREAMING_SNAKE_CASE_ ) ) # Size of every segment lowercase__ : Dict = [True] * (end + 1) lowercase__ : Union[str, Any] = [] while start <= end: if temp[start] is True: in_prime.append(SCREAMING_SNAKE_CASE_ ) for i in range(start * start , end + 1 , SCREAMING_SNAKE_CASE_ ): lowercase__ : int = False start += 1 prime += in_prime lowercase__ : Optional[int] = end + 1 lowercase__ : List[str] = min(2 * end , SCREAMING_SNAKE_CASE_ ) while low <= n: lowercase__ : str = [True] * (high - low + 1) for each in in_prime: lowercase__ : str = math.floor(low / each ) * each if t < low: t += each for j in range(SCREAMING_SNAKE_CASE_ , high + 1 , SCREAMING_SNAKE_CASE_ ): lowercase__ : Optional[Any] = False for j in range(len(SCREAMING_SNAKE_CASE_ ) ): if temp[j] is True: prime.append(j + low ) lowercase__ : Optional[Any] = high + 1 lowercase__ : Optional[int] = min(high + end , SCREAMING_SNAKE_CASE_ ) return prime print(sieve(10**6))
214
0
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowerCAmelCase__ ( _a : List[str] , _a : str , _a : Dict=10_24 , _a : str=10_24 , _a : int=False , **_a : int ): snake_case_ : int = AutoTokenizer.from_pretrained(_a ) snake_case_ : str = SeqaSeqDataset(_a , _a , _a , _a , type_path="train" , **_a ) snake_case_ : Any = tok.pad_token_id def get_lens(_a : List[str] ): snake_case_ : Optional[Any] = tqdm( DataLoader(_a , batch_size=5_12 , num_workers=8 , shuffle=_a , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) snake_case_ : List[Any] = [] for batch in dl: snake_case_ : List[str] = batch["input_ids"].ne(_a ).sum(1 ).tolist() snake_case_ : Union[str, Any] = batch["labels"].ne(_a ).sum(1 ).tolist() if consider_target: for src, tgt in zip(_a , _a ): max_lens.append(max(_a , _a ) ) else: max_lens.extend(_a ) return max_lens snake_case_ : Dict = get_lens(_a ) snake_case_ : List[Any] = SeqaSeqDataset(_a , _a , _a , _a , type_path="val" , **_a ) snake_case_ : str = get_lens(_a ) pickle_save(_a , train_ds.len_file ) pickle_save(_a , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
36
def lowerCAmelCase__ ( _a : int = 50 ): snake_case_ : Union[str, Any] = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
36
1
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _snake_case ( snake_case__ : Dict , snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : List[str] , ): A , A = coefficient_matrix.shape A , A = constant_matrix.shape if rowsa != colsa: A = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(snake_case__ ) if colsa != 1: A = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(snake_case__ ) if rowsa != rowsa: A = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(snake_case__ ) if len(snake_case__ ) != rowsa: A = ( 'Number of initial values must be equal to number of rows in coefficient ' F'matrix but received {len(snake_case__ )} and {rowsa}' ) raise ValueError(snake_case__ ) if iterations <= 0: raise ValueError('Iterations must be at least 1' ) A = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) A , A = table.shape strictly_diagonally_dominant(snake_case__ ) # Iterates the whole matrix for given number of times for _ in range(snake_case__ ): A = [] for row in range(snake_case__ ): A = 0 for col in range(snake_case__ ): if col == row: A = table[row][col] elif col == cols - 1: A = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] A = (temp + val) / denom new_val.append(snake_case__ ) A = new_val return [float(snake_case__ ) for i in new_val] def _snake_case ( snake_case__ : List[str] ): A , A = table.shape A = True for i in range(0 , snake_case__ ): A = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('Coefficient matrix is not strictly diagonally dominant' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase__ : Tuple = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[Any] = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : int = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowerCAmelCase__ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
98
0
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput UpperCAmelCase__ = "scheduler_config.json" class __lowerCAmelCase ( __lowerCAmelCase ): UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 3 UpperCamelCase = 4 UpperCamelCase = 5 @dataclass class __lowerCAmelCase ( __lowerCAmelCase ): UpperCamelCase = 42 class __lowerCAmelCase : UpperCamelCase = SCHEDULER_CONFIG_NAME UpperCamelCase = ["dtype"] UpperCamelCase = [] UpperCamelCase = True @classmethod def _lowerCamelCase ( cls : int , A : Dict[str, Any] = None , A : Optional[str] = None , A : int=False , **A : Optional[int] , ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = cls.load_config( pretrained_model_name_or_path=lowerCamelCase__ , subfolder=lowerCamelCase__ , return_unused_kwargs=lowerCamelCase__ , **lowerCamelCase__ , ) _UpperCAmelCase = cls.from_config(lowerCamelCase__ , return_unused_kwargs=lowerCamelCase__ , **lowerCamelCase__) if hasattr(lowerCamelCase__ , 'create_state') and getattr(lowerCamelCase__ , 'has_state' , lowerCamelCase__): _UpperCAmelCase = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def _lowerCamelCase ( self : Optional[Any] , A : Union[str, os.PathLike] , A : bool = False , **A : Optional[Any]) -> str: """simple docstring""" self.save_config(save_directory=lowerCamelCase__ , push_to_hub=lowerCamelCase__ , **lowerCamelCase__) @property def _lowerCamelCase ( self : List[str]) -> Tuple: """simple docstring""" return self._get_compatibles() @classmethod def _lowerCamelCase ( cls : Optional[int]) -> Any: """simple docstring""" _UpperCAmelCase = list(set([cls.__name__] + cls._compatibles)) _UpperCAmelCase = importlib.import_module(__name__.split('.')[0]) _UpperCAmelCase = [ getattr(lowerCamelCase__ , lowerCamelCase__) for c in compatible_classes_str if hasattr(lowerCamelCase__ , lowerCamelCase__) ] return compatible_classes def A ( _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : Tuple[int] ) -> Optional[int]: '''simple docstring''' assert len(_UpperCAmelCase ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(_UpperCAmelCase ) - x.ndim) ) , _UpperCAmelCase ) def A ( _UpperCAmelCase : int , _UpperCAmelCase : Dict=0.999 , _UpperCAmelCase : Tuple=jnp.floataa ) -> Tuple: '''simple docstring''' def alpha_bar(_UpperCAmelCase : Tuple ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 _UpperCAmelCase = [] for i in range(_UpperCAmelCase ): _UpperCAmelCase = i / num_diffusion_timesteps _UpperCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(_UpperCAmelCase ) / alpha_bar(_UpperCAmelCase ) , _UpperCAmelCase ) ) return jnp.array(_UpperCAmelCase , dtype=_UpperCAmelCase ) @flax.struct.dataclass class __lowerCAmelCase : UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 @classmethod def _lowerCamelCase ( cls : List[Any] , A : Union[str, Any]) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = scheduler.config if config.trained_betas is not None: _UpperCAmelCase = jnp.asarray(config.trained_betas , dtype=scheduler.dtype) elif config.beta_schedule == "linear": _UpperCAmelCase = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _UpperCAmelCase = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _UpperCAmelCase = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype) else: raise NotImplementedError( F"beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}") _UpperCAmelCase = 1.0 - betas _UpperCAmelCase = jnp.cumprod(lowerCamelCase__ , axis=0) return cls( alphas=lowerCamelCase__ , betas=lowerCamelCase__ , alphas_cumprod=lowerCamelCase__ , ) def A ( _UpperCAmelCase : CommonSchedulerState , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = state.alphas_cumprod _UpperCAmelCase = alphas_cumprod[timesteps] ** 0.5 _UpperCAmelCase = sqrt_alpha_prod.flatten() _UpperCAmelCase = broadcast_to_shape_from_left(_UpperCAmelCase , original_samples.shape ) _UpperCAmelCase = (1 - alphas_cumprod[timesteps]) ** 0.5 _UpperCAmelCase = sqrt_one_minus_alpha_prod.flatten() _UpperCAmelCase = broadcast_to_shape_from_left(_UpperCAmelCase , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def A ( _UpperCAmelCase : CommonSchedulerState , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray ) -> Dict: '''simple docstring''' _UpperCAmelCase = get_sqrt_alpha_prod(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) _UpperCAmelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def A ( _UpperCAmelCase : CommonSchedulerState , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray , _UpperCAmelCase : jnp.ndarray ) -> Dict: '''simple docstring''' _UpperCAmelCase = get_sqrt_alpha_prod(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) _UpperCAmelCase = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
357
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( A ): def _lowerCamelCase ( self : List[str]) -> int: """simple docstring""" _UpperCAmelCase = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(A , 'hidden_sizes')) self.parent.assertTrue(hasattr(A , 'neck_hidden_sizes')) self.parent.assertTrue(hasattr(A , 'num_attention_heads')) class __lowerCAmelCase : def __init__( self : int , A : Tuple , A : List[str]=13 , A : List[str]=32 , A : List[str]=2 , A : List[str]=3 , A : List[Any]=6_40 , A : Any=4 , A : int="silu" , A : int=3 , A : Dict=32 , A : List[Any]=0.1 , A : Optional[Any]=0.1 , A : Optional[int]=0.1 , A : List[str]=0.0_2 , A : int=True , A : Any=True , A : List[str]=10 , A : Tuple=None , ) -> Dict: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = last_hidden_size _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = output_stride _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = classifier_dropout_prob _UpperCAmelCase = use_labels _UpperCAmelCase = is_training _UpperCAmelCase = num_labels _UpperCAmelCase = initializer_range _UpperCAmelCase = scope def _lowerCamelCase ( self : Union[str, Any]) -> Any: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_labels) _UpperCAmelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) _UpperCAmelCase = self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCamelCase ( self : str) -> int: """simple docstring""" return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowerCamelCase ( self : List[Any] , A : Dict , A : Tuple , A : int , A : Tuple) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MobileViTModel(config=A) model.to(A) model.eval() _UpperCAmelCase = model(A) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowerCamelCase ( self : int , A : Any , A : List[Any] , A : List[Any] , A : Optional[int]) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.num_labels _UpperCAmelCase = MobileViTForImageClassification(A) model.to(A) model.eval() _UpperCAmelCase = model(A , labels=A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _lowerCamelCase ( self : int , A : Tuple , A : Optional[Any] , A : Union[str, Any] , A : List[Any]) -> int: """simple docstring""" _UpperCAmelCase = self.num_labels _UpperCAmelCase = MobileViTForSemanticSegmentation(A) model.to(A) model.eval() _UpperCAmelCase = model(A) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _UpperCAmelCase = model(A , labels=A) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowerCamelCase ( self : int) -> Any: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( A , A , unittest.TestCase ): UpperCamelCase = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase = ( { '''feature-extraction''': MobileViTModel, '''image-classification''': MobileViTForImageClassification, '''image-segmentation''': MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def _lowerCamelCase ( self : str) -> Tuple: """simple docstring""" _UpperCAmelCase = MobileViTModelTester(self) _UpperCAmelCase = MobileViTConfigTester(self , config_class=A , has_text_modality=A) def _lowerCamelCase ( self : Optional[int]) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='MobileViT does not use inputs_embeds') def _lowerCamelCase ( self : Tuple) -> Dict: """simple docstring""" pass @unittest.skip(reason='MobileViT does not support input and output embeddings') def _lowerCamelCase ( self : Optional[Any]) -> List[Any]: """simple docstring""" pass @unittest.skip(reason='MobileViT does not output attentions') def _lowerCamelCase ( self : Any) -> Optional[Any]: """simple docstring""" pass def _lowerCamelCase ( self : List[Any]) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(A) _UpperCAmelCase = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , A) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.') def _lowerCamelCase ( self : Union[str, Any]) -> List[str]: """simple docstring""" pass def _lowerCamelCase ( self : Tuple) -> str: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A) def _lowerCamelCase ( self : Optional[int]) -> Any: """simple docstring""" def check_hidden_states_output(A : List[str] , A : Union[str, Any] , A : int): _UpperCAmelCase = model_class(A) model.to(A) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(A , A)) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = 5 self.assertEqual(len(A) , A) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. _UpperCAmelCase = 2 for i in range(len(A)): self.assertListEqual( list(hidden_states[i].shape[-2:]) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2) _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = True check_hidden_states_output(A , A , A) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True check_hidden_states_output(A , A , A) def _lowerCamelCase ( self : List[str]) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A) def _lowerCamelCase ( self : int) -> Tuple: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*A) @slow def _lowerCamelCase ( self : Optional[int]) -> Union[str, Any]: """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = MobileViTModel.from_pretrained(A) self.assertIsNotNone(A) def A ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def _lowerCamelCase ( self : Tuple) -> Dict: """simple docstring""" return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small') if is_vision_available() else None @slow def _lowerCamelCase ( self : List[Any]) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small').to(A) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=A , return_tensors='pt').to(A) # forward pass with torch.no_grad(): _UpperCAmelCase = model(**A) # verify the logits _UpperCAmelCase = torch.Size((1, 10_00)) self.assertEqual(outputs.logits.shape , A) _UpperCAmelCase = torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]).to(A) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A , atol=1E-4)) @slow def _lowerCamelCase ( self : List[Any]) -> List[str]: """simple docstring""" _UpperCAmelCase = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small') _UpperCAmelCase = model.to(A) _UpperCAmelCase = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small') _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=A , return_tensors='pt').to(A) # forward pass with torch.no_grad(): _UpperCAmelCase = model(**A) _UpperCAmelCase = outputs.logits # verify the logits _UpperCAmelCase = torch.Size((1, 21, 32, 32)) self.assertEqual(logits.shape , A) _UpperCAmelCase = torch.tensor( [ [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]], [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]], [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]], ] , device=A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , A , atol=1E-4)) @slow def _lowerCamelCase ( self : List[Any]) -> List[str]: """simple docstring""" _UpperCAmelCase = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small') _UpperCAmelCase = model.to(A) _UpperCAmelCase = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small') _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=A , return_tensors='pt').to(A) # forward pass with torch.no_grad(): _UpperCAmelCase = model(**A) _UpperCAmelCase = outputs.logits.detach().cpu() _UpperCAmelCase = image_processor.post_process_semantic_segmentation(outputs=A , target_sizes=[(50, 60)]) _UpperCAmelCase = torch.Size((50, 60)) self.assertEqual(segmentation[0].shape , A) _UpperCAmelCase = image_processor.post_process_semantic_segmentation(outputs=A) _UpperCAmelCase = torch.Size((32, 32)) self.assertEqual(segmentation[0].shape , A)
290
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class snake_case : """simple docstring""" _lowerCamelCase = MBartConfig _lowerCamelCase = {} _lowerCamelCase = "gelu" def __init__( self , UpperCamelCase , UpperCamelCase=13 , UpperCamelCase=7 , UpperCamelCase=True , UpperCamelCase=False , UpperCamelCase=99 , UpperCamelCase=32 , UpperCamelCase=2 , UpperCamelCase=4 , UpperCamelCase=37 , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=20 , UpperCamelCase=2 , UpperCamelCase=1 , UpperCamelCase=0 , ): """simple docstring""" lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = seq_length lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = eos_token_id lowerCamelCase_ = pad_token_id lowerCamelCase_ = bos_token_id def snake_case ( self ): """simple docstring""" lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCamelCase_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCamelCase_ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ = 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 , ) lowerCamelCase_ = prepare_mbart_inputs_dict(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return config, inputs_dict def snake_case ( self , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = TFMBartModel(config=UpperCamelCase ).get_decoder() lowerCamelCase_ = inputs_dict["input_ids"] lowerCamelCase_ = input_ids[:1, :] lowerCamelCase_ = inputs_dict["attention_mask"][:1, :] lowerCamelCase_ = inputs_dict["head_mask"] lowerCamelCase_ = 1 # first forward pass lowerCamelCase_ = model(UpperCamelCase , attention_mask=UpperCamelCase , head_mask=UpperCamelCase , use_cache=UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = outputs.to_tuple() lowerCamelCase_ = past_key_values[1] def __snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=None , ): if attention_mask is None: lowerCamelCase_ = tf.cast(tf.math.not_equal(UpperCAmelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCamelCase_ = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowerCamelCase_ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCamelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCamelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class snake_case ( lowercase , lowercase , unittest.TestCase ): """simple docstring""" _lowerCamelCase = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () _lowerCamelCase = (TFMBartForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase = ( { "conversational": TFMBartForConditionalGeneration, "feature-extraction": TFMBartModel, "summarization": TFMBartForConditionalGeneration, "text2text-generation": TFMBartForConditionalGeneration, "translation": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase = True _lowerCamelCase = False _lowerCamelCase = False def snake_case ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def snake_case ( self ): """simple docstring""" lowerCamelCase_ = TFMBartModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=UpperCamelCase ) def snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class snake_case ( unittest.TestCase ): """simple docstring""" _lowerCamelCase = [ " UN Chief Says There Is No Military Solution in Syria", ] _lowerCamelCase = [ "Şeful ONU declară că nu există o soluţie militară în Siria", ] _lowerCamelCase = "facebook/mbart-large-en-ro" @cached_property def snake_case ( self ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case ( self ): """simple docstring""" lowerCamelCase_ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case ( self , **UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.translate_src_text(**UpperCamelCase ) self.assertListEqual(self.expected_text , UpperCamelCase ) def snake_case ( self , **UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.tokenizer(self.src_text , **UpperCamelCase , return_tensors="tf" ) lowerCamelCase_ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) lowerCamelCase_ = self.tokenizer.batch_decode(UpperCamelCase , skip_special_tokens=UpperCamelCase ) return generated_words @slow def snake_case ( self ): """simple docstring""" self._assert_generated_batch_equal_expected()
55
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] ={ '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] =[ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys A__ : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
0
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" A__ = FunnelConfig.from_json_file(_a ) print(F'''Building PyTorch model from configuration: {config}''' ) A__ = FunnelBaseModel(_a ) if base_model else FunnelModel(_a ) # Load weights from tf checkpoint load_tf_weights_in_funnel(_a , _a , _a ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , _a ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." ) __lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
361
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase = { "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
154
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin _lowerCamelCase : Tuple = random.Random() def __lowerCamelCase ( A__ , A__=1.0 , A__=None , A__=None ) -> Union[str, Any]: """simple docstring""" if rng is None: UpperCamelCase = global_rng UpperCamelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any]=7 , UpperCamelCase__ : List[str]=4_0_0 , UpperCamelCase__ : str=2_0_0_0 , UpperCamelCase__ : Any=1 , UpperCamelCase__ : Optional[Any]=0.0 , UpperCamelCase__ : Tuple=1_6_0_0_0 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Dict=True , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = min_seq_length UpperCamelCase = max_seq_length UpperCamelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase = feature_size UpperCamelCase = padding_value UpperCamelCase = sampling_rate UpperCamelCase = return_attention_mask UpperCamelCase = do_normalize def A ( self : Optional[int] ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def A ( self : Union[str, Any] , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Union[str, Any]=False ): """simple docstring""" def _flatten(UpperCamelCase__ : Optional[Any] ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: UpperCamelCase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs class SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = WavaVecaFeatureExtractionTester(self ) def A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): """simple docstring""" self.assertTrue(np.all(np.mean(UpperCamelCase__ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(UpperCamelCase__ , axis=0 ) - 1 ) < 1E-3 ) ) def A ( self : Optional[int] ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values UpperCamelCase = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) # Test batched UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] UpperCamelCase = np.asarray(UpperCamelCase__ ) UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values UpperCamelCase = feat_extract(UpperCamelCase__ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase = [None, 1_6_0_0, None] for max_length, padding in zip(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = feat_extract(UpperCamelCase__ , padding=UpperCamelCase__ , max_length=UpperCamelCase__ , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 ) UpperCamelCase = [floats_list((1, x) )[0] for x in lengths] UpperCamelCase = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase = [None, 1_6_0_0, None] for max_length, padding in zip(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = feat_extract(UpperCamelCase__ , max_length=UpperCamelCase__ , padding=UpperCamelCase__ ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self : str ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=1_0_0_0 , padding='max_length' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def A ( self : Tuple ): """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=1_0_0_0 , padding='longest' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) UpperCamelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase = feat_extract( UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=2_0_0_0 , padding='longest' , return_tensors='np' ) UpperCamelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) @require_torch def A ( self : Optional[Any] ): """simple docstring""" import torch UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = np.random.rand(1_0_0 ).astype(np.floataa ) UpperCamelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def A ( self : Any ): """simple docstring""" for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: UpperCamelCase = WavaVecaConfig.from_pretrained(UpperCamelCase__ ) UpperCamelCase = WavaVecaFeatureExtractor.from_pretrained(UpperCamelCase__ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == 'layer' )
28
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) __a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __a : List[str] = components[:-1] + [test_fn.replace('.py' , '' )] __a : Optional[Any] = '.'.join(_SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = get_module_path(_SCREAMING_SNAKE_CASE ) __a : Dict = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : List[str] = [] __a : List[str] = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : Any = [] __a : str = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): __a : int = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = test_class() if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ): test.setUp() __a : List[Any] = None if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __a : List[str] = test.model_tester.__class__ return model_tester def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Any = [] for test_class in test_classes: __a : Any = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : str = get_test_classes(_SCREAMING_SNAKE_CASE ) __a : int = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Optional[Any] = get_model_classes(_SCREAMING_SNAKE_CASE ) __a : str = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
27
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): __SCREAMING_SNAKE_CASE = StableDiffusionXLImgaImgPipeline __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __SCREAMING_SNAKE_CASE = PipelineTesterMixin.required_optional_params - {'''latents'''} __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase ( self ): torch.manual_seed(0 ) A__ = UNetaDConditionModel( block_out_channels=(32, 64),layers_per_block=2,sample_size=32,in_channels=4,out_channels=4,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),attention_head_dim=(2, 4),use_linear_projection=__lowerCamelCase,addition_embed_type='''text_time''',addition_time_embed_dim=8,transformer_layers_per_block=(1, 2),projection_class_embeddings_input_dim=80,cross_attention_dim=64,) A__ = EulerDiscreteScheduler( beta_start=0.00085,beta_end=0.012,steps_offset=1,beta_schedule='''scaled_linear''',timestep_spacing='''leading''',) torch.manual_seed(0 ) A__ = AutoencoderKL( block_out_channels=[32, 64],in_channels=3,out_channels=3,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],latent_channels=4,sample_size=128,) torch.manual_seed(0 ) A__ = CLIPTextConfig( bos_token_id=0,eos_token_id=2,hidden_size=32,intermediate_size=37,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1000,hidden_act='''gelu''',projection_dim=32,) A__ = CLIPTextModel(__lowerCamelCase ) A__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''',local_files_only=__lowerCamelCase ) A__ = CLIPTextModelWithProjection(__lowerCamelCase ) A__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''',local_files_only=__lowerCamelCase ) A__ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''text_encoder_2''': text_encoder_a, '''tokenizer_2''': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase=0 ): A__ = floats_tensor((1, 3, 32, 32),rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) A__ = image / 2 + 0.5 if str(__lowerCamelCase ).startswith('''mps''' ): A__ = torch.manual_seed(__lowerCamelCase ) else: A__ = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) A__ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 5.0, '''output_type''': '''numpy''', '''strength''': 0.75, } return inputs def UpperCamelCase ( self ): A__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator A__ = self.get_dummy_components() A__ = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) A__ = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) A__ = self.get_dummy_inputs(__lowerCamelCase ) A__ = sd_pipe(**__lowerCamelCase ).images A__ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase ( self ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def UpperCamelCase ( self ): pass def UpperCamelCase ( self ): A__ = self.get_dummy_components() A__ = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) A__ = sd_pipe.to(__lowerCamelCase ) A__ = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds A__ = self.get_dummy_inputs(__lowerCamelCase ) A__ = 3 * ['''this is a negative prompt'''] A__ = negative_prompt A__ = 3 * [inputs['''prompt''']] A__ = sd_pipe(**__lowerCamelCase ) A__ = output.images[0, -3:, -3:, -1] # forward with prompt embeds A__ = self.get_dummy_inputs(__lowerCamelCase ) A__ = 3 * ['''this is a negative prompt'''] A__ = 3 * [inputs.pop('''prompt''' )] ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = sd_pipe.encode_prompt(__lowerCamelCase,negative_prompt=__lowerCamelCase ) A__ = sd_pipe( **__lowerCamelCase,prompt_embeds=__lowerCamelCase,negative_prompt_embeds=__lowerCamelCase,pooled_prompt_embeds=__lowerCamelCase,negative_pooled_prompt_embeds=__lowerCamelCase,) A__ = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase="cpu",__lowerCamelCase=torch.floataa,__lowerCamelCase=0 ): A__ = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) A__ = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) A__ = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase,dtype=__lowerCamelCase ) A__ = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def UpperCamelCase ( self ): A__ = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) A__ = self.get_inputs(__lowerCamelCase ) A__ = pipe(**__lowerCamelCase ).images A__ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) A__ = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
39
def UpperCamelCase__( UpperCamelCase__ : int = 1_00 )->int: A__ = (n * (n + 1) // 2) ** 2 A__ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F"{solution() = }")
39
1
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = CodeGenTokenizer __lowerCamelCase : Any = CodeGenTokenizerFast __lowerCamelCase : Any = True __lowerCamelCase : Any = {"add_prefix_space": True} __lowerCamelCase : int = False def _lowerCAmelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] A : List[str] = dict(zip(lowerCamelCase__, range(len(lowerCamelCase__ ) ) ) ) A : List[Any] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] A : int = {"""unk_token""": """<unk>"""} A : Union[str, Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) A : Union[str, Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file, """w""", encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCamelCase__ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase__ ) ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__ ): A : Dict = """lower newer""" A : Any = """lower newer""" return input_text, output_text def _lowerCAmelCase ( self ): A : int = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) A : Any = """lower newer""" A : Optional[Any] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] A : Optional[Any] = tokenizer.tokenize(lowerCamelCase__, add_prefix_space=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) A : Any = tokens + [tokenizer.unk_token] A : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__ ), lowerCamelCase__ ) def _lowerCAmelCase ( self ): if not self.test_rust_tokenizer: return A : str = self.get_tokenizer() A : str = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase__ ) A : Any = """lower newer""" # Testing tokenization A : str = tokenizer.tokenize(lowerCamelCase__, add_prefix_space=lowerCamelCase__ ) A : Dict = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) # Testing conversion to ids without special tokens A : Union[str, Any] = tokenizer.encode(lowerCamelCase__, add_special_tokens=lowerCamelCase__, add_prefix_space=lowerCamelCase__ ) A : int = rust_tokenizer.encode(lowerCamelCase__, add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) # Testing conversion to ids with special tokens A : List[Any] = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase__ ) A : Union[str, Any] = tokenizer.encode(lowerCamelCase__, add_prefix_space=lowerCamelCase__ ) A : Any = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) # Testing the unknown token A : Tuple = tokens + [rust_tokenizer.unk_token] A : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowerCamelCase__ ), lowerCamelCase__ ) def _lowerCAmelCase ( self, *lowerCamelCase__, **lowerCamelCase__ ): # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _lowerCAmelCase ( self, lowerCamelCase__=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): A : Any = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__, **lowerCamelCase__ ) # Simple input A : Tuple = """This is a simple input""" A : List[Any] = ["""This is a simple input 1""", """This is a simple input 2"""] A : Union[str, Any] = ("""This is a simple input""", """This is a pair""") A : List[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(lowerCamelCase__, tokenizer_r.encode, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Simple input self.assertRaises(lowerCamelCase__, tokenizer_r.encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Simple input self.assertRaises( lowerCamelCase__, tokenizer_r.batch_encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""", ) # Pair input self.assertRaises(lowerCamelCase__, tokenizer_r.encode, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Pair input self.assertRaises(lowerCamelCase__, tokenizer_r.encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Pair input self.assertRaises( lowerCamelCase__, tokenizer_r.batch_encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""", ) def _lowerCAmelCase ( self ): A : str = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input A : Optional[Any] = """This is a simple input""" A : List[str] = ["""This is a simple input looooooooong""", """This is a simple input"""] A : int = ("""This is a simple input""", """This is a pair""") A : Union[str, Any] = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] A : List[Any] = tokenizer.pad_token_id A : Dict = tokenizer(lowerCamelCase__, padding="""max_length""", max_length=30, return_tensors="""np""" ) A : Optional[int] = tokenizer(lowerCamelCase__, padding=lowerCamelCase__, truncate=lowerCamelCase__, return_tensors="""np""" ) A : Union[str, Any] = tokenizer(*lowerCamelCase__, padding="""max_length""", max_length=60, return_tensors="""np""" ) A : Dict = tokenizer(lowerCamelCase__, padding=lowerCamelCase__, truncate=lowerCamelCase__, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def _lowerCAmelCase ( self ): A : str = """$$$""" A : Tuple = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=lowerCamelCase__, add_bos_token=lowerCamelCase__ ) A : Union[str, Any] = """This is a simple input""" A : Union[str, Any] = ["""This is a simple input 1""", """This is a simple input 2"""] A : Dict = tokenizer.bos_token_id A : List[Any] = tokenizer(lowerCamelCase__ ) A : str = tokenizer(lowerCamelCase__ ) self.assertEqual(out_s.input_ids[0], lowerCamelCase__ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) A : Optional[int] = tokenizer.decode(out_s.input_ids ) A : Tuple = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], lowerCamelCase__ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def _lowerCAmelCase ( self ): A : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) A : Union[str, Any] = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" A : Any = """\nif len_a > len_b: result = a\nelse: result = b""" A : Optional[int] = tokenizer.encode(lowerCamelCase__ ) A : Tuple = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] A : Any = tokenizer.decode(lowerCamelCase__, truncate_before_pattern=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): pass
116
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__=13, lowerCamelCase__=7, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=99, lowerCamelCase__=32, lowerCamelCase__=5, lowerCamelCase__=4, lowerCamelCase__=37, lowerCamelCase__="gelu", lowerCamelCase__=0.1, lowerCamelCase__=0.1, lowerCamelCase__=512, lowerCamelCase__=16, lowerCamelCase__=2, lowerCamelCase__=0.02, lowerCamelCase__=4, ): A : List[str] = parent A : Optional[int] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : List[str] = use_attention_mask A : Union[str, Any] = use_token_type_ids A : Any = use_labels A : str = vocab_size A : Union[str, Any] = hidden_size A : str = num_hidden_layers A : List[Any] = num_attention_heads A : Optional[int] = intermediate_size A : Optional[Any] = hidden_act A : Dict = hidden_dropout_prob A : List[Any] = attention_probs_dropout_prob A : Optional[int] = max_position_embeddings A : int = type_vocab_size A : str = type_sequence_label_size A : List[Any] = initializer_range A : str = num_choices def _lowerCAmelCase ( self ): A : Optional[int] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) A : Union[str, Any] = None if self.use_attention_mask: A : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) A : int = None if self.use_token_type_ids: A : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) A : Optional[int] = AlbertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=lowerCamelCase__, initializer_range=self.initializer_range, ) return config, input_ids, token_type_ids, attention_mask def _lowerCAmelCase ( self ): A : Dict = self.prepare_config_and_inputs() A , A , A , A : str = config_and_inputs A : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Any = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def _lowerCAmelCase ( self ): A : Dict = FlaxAlbertModelTester(self ) @slow def _lowerCAmelCase ( self ): for model_class_name in self.all_model_classes: A : Dict = model_class_name.from_pretrained("""albert-base-v2""" ) A : Optional[int] = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase__ ) @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @slow def _lowerCAmelCase ( self ): A : Dict = FlaxAlbertModel.from_pretrained("""albert-base-v2""" ) A : List[str] = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) A : str = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) A : Optional[int] = model(lowerCamelCase__, attention_mask=lowerCamelCase__ )[0] A : str = (1, 11, 768) self.assertEqual(output.shape, lowerCamelCase__ ) A : Optional[int] = np.array( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4], lowerCamelCase__, atol=1e-4 ) )
116
1
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib _SCREAMING_SNAKE_CASE = get_logger() _SCREAMING_SNAKE_CASE = None class _lowerCAmelCase ( TensorFormatter[Mapping, "jax.Array", Mapping] ): """simple docstring""" def __init__( self : Optional[Any] , __snake_case : Dict=None , __snake_case : Any=None , **__snake_case : Any )-> List[Any]: super().__init__(features=__snake_case ) import jax from jaxlib.xla_client import Device if isinstance(__snake_case , __snake_case ): raise ValueError( f'''Expected {device} to be a `str` not {type(__snake_case )}, as `jaxlib.xla_extension.Device` ''' """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """ """the device with `str()` to get its string identifier that will be internally mapped """ """to the actual `jaxlib.xla_extension.Device`.""" ) snake_case = device if isinstance(__snake_case , __snake_case ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) snake_case = str(jax.devices()[0] ) snake_case = jnp_array_kwargs @staticmethod def lowerCAmelCase ( )-> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(__snake_case ): device for device in jax.devices()} def lowerCAmelCase ( self : Dict , __snake_case : str )-> Optional[int]: import jax import jax.numpy as jnp if isinstance(__snake_case , __snake_case ) and column: if all( isinstance(__snake_case , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__snake_case , axis=0 ) return column def lowerCAmelCase ( self : Optional[int] , __snake_case : Optional[Any] )-> Union[str, Any]: import jax import jax.numpy as jnp if isinstance(__snake_case , (str, bytes, type(__snake_case )) ): return value elif isinstance(__snake_case , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() snake_case = {} if isinstance(__snake_case , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: snake_case = {"""dtype""": jnp.intaa} else: snake_case = {"""dtype""": jnp.intaa} elif isinstance(__snake_case , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): snake_case = {"""dtype""": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__snake_case , PIL.Image.Image ): snake_case = np.asarray(__snake_case ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__snake_case , **{**default_dtype, **self.jnp_array_kwargs} ) def lowerCAmelCase ( self : List[Any] , __snake_case : Tuple )-> List[Any]: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__snake_case , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__snake_case , """__array__""" ) and not isinstance(__snake_case , jax.Array ): snake_case = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__snake_case , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__snake_case ) for substruct in data_struct] ) elif isinstance(__snake_case , (list, tuple) ): return self._consolidate([self.recursive_tensorize(__snake_case ) for substruct in data_struct] ) return self._tensorize(__snake_case ) def lowerCAmelCase ( self : Optional[int] , __snake_case : dict )-> str: return map_nested(self._recursive_tensorize , __snake_case , map_list=__snake_case ) def lowerCAmelCase ( self : List[str] , __snake_case : pa.Table )-> Mapping: snake_case = self.numpy_arrow_extractor().extract_row(__snake_case ) snake_case = self.python_features_decoder.decode_row(__snake_case ) return self.recursive_tensorize(__snake_case ) def lowerCAmelCase ( self : Union[str, Any] , __snake_case : pa.Table )-> "jax.Array": snake_case = self.numpy_arrow_extractor().extract_column(__snake_case ) snake_case = self.python_features_decoder.decode_column(__snake_case , pa_table.column_names[0] ) snake_case = self.recursive_tensorize(__snake_case ) snake_case = self._consolidate(__snake_case ) return column def lowerCAmelCase ( self : Any , __snake_case : pa.Table )-> Mapping: snake_case = self.numpy_arrow_extractor().extract_batch(__snake_case ) snake_case = self.python_features_decoder.decode_batch(__snake_case ) snake_case = self.recursive_tensorize(__snake_case ) for column_name in batch: snake_case = self._consolidate(batch[column_name] ) return batch
3
'''simple docstring''' import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __lowerCamelCase ( __lowerCAmelCase : dict ) -> tuple: return (data["data"], data["target"]) def __lowerCamelCase ( __lowerCAmelCase : np.ndarray , __lowerCAmelCase : np.ndarray ) -> XGBClassifier: snake_case = XGBClassifier() classifier.fit(__lowerCAmelCase , __lowerCAmelCase ) return classifier def __lowerCamelCase ( ) -> None: snake_case = load_iris() snake_case , snake_case = data_handling(__lowerCAmelCase ) snake_case , snake_case , snake_case , snake_case = train_test_split( __lowerCAmelCase , __lowerCAmelCase , test_size=0.25 ) snake_case = iris["""target_names"""] # Create an XGBoost Classifier from the training data snake_case = xgboost(__lowerCAmelCase , __lowerCAmelCase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , display_labels=__lowerCAmelCase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
3
1
"""simple docstring""" import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors A : Union[str, Any] = logging.getLogger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[Any] ="""sequence-classification""" def __init__( self , __a ): if type(__a ) == dict: __lowerCAmelCase = Namespace(**__a ) __lowerCAmelCase = glue_output_modes[hparams.task] __lowerCAmelCase = glue_tasks_num_labels[hparams.task] super().__init__(__a , __a , self.mode ) def snake_case ( self , **__a ): return self.model(**__a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __lowerCAmelCase = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __lowerCAmelCase = self(**__a ) __lowerCAmelCase = outputs[0] __lowerCAmelCase = self.trainer.lr_schedulers[0]["scheduler"] __lowerCAmelCase = {"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def snake_case ( self ): __lowerCAmelCase = self.hparams __lowerCAmelCase = processors[args.task]() __lowerCAmelCase = processor.get_labels() for mode in ["train", "dev"]: __lowerCAmelCase = self._feature_file(__a ) if os.path.exists(__a ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , __a ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) __lowerCAmelCase = ( processor.get_dev_examples(args.data_dir ) if mode == "dev" else processor.get_train_examples(args.data_dir ) ) __lowerCAmelCase = convert_examples_to_features( __a , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("Saving features into cached file %s" , __a ) torch.save(__a , __a ) def snake_case ( self , __a , __a , __a = False ): __lowerCAmelCase = "dev" if mode == "test" else mode __lowerCAmelCase = self._feature_file(__a ) logger.info("Loading features from cached file %s" , __a ) __lowerCAmelCase = torch.load(__a ) __lowerCAmelCase = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __lowerCAmelCase = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __lowerCAmelCase = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __lowerCAmelCase = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __lowerCAmelCase = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__a , __a , __a , __a ) , batch_size=__a , shuffle=__a , ) def snake_case ( self , __a , __a ): __lowerCAmelCase = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __lowerCAmelCase = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __lowerCAmelCase = self(**__a ) __lowerCAmelCase , __lowerCAmelCase = outputs[:2] __lowerCAmelCase = logits.detach().cpu().numpy() __lowerCAmelCase = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def snake_case ( self , __a ): __lowerCAmelCase = torch.stack([x["val_loss"] for x in outputs] ).mean().detach().cpu().item() __lowerCAmelCase = np.concatenate([x["pred"] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __lowerCAmelCase = np.argmax(__a , axis=1 ) elif self.hparams.glue_output_mode == "regression": __lowerCAmelCase = np.squeeze(__a ) __lowerCAmelCase = np.concatenate([x["target"] for x in outputs] , axis=0 ) __lowerCAmelCase = [[] for _ in range(out_label_ids.shape[0] )] __lowerCAmelCase = [[] for _ in range(out_label_ids.shape[0] )] __lowerCAmelCase = {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task , __a , __a )} __lowerCAmelCase = dict(results.items() ) __lowerCAmelCase = results return ret, preds_list, out_label_list def snake_case ( self , __a ): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self._eval_end(__a ) __lowerCAmelCase = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def snake_case ( self , __a ): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self._eval_end(__a ) __lowerCAmelCase = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def snake_case ( __a , __a ): BaseTransformer.add_model_specific_args(__a , __a ) parser.add_argument( "--max_seq_length" , default=1_28 , type=__a , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--task" , default="" , type=__a , required=__a , help="The GLUE task to run" , ) parser.add_argument( "--gpus" , default=0 , type=__a , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = argparse.ArgumentParser() add_generic_args(_UpperCamelCase , os.getcwd() ) __lowerCAmelCase = GLUETransformer.add_model_specific_args(_UpperCamelCase , os.getcwd() ) __lowerCAmelCase = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __lowerCAmelCase = os.path.join( "./results" , f"{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}" , ) os.makedirs(args.output_dir ) __lowerCAmelCase = GLUETransformer(_UpperCamelCase ) __lowerCAmelCase = generic_train(_UpperCamelCase , _UpperCamelCase ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __lowerCAmelCase = sorted(glob.glob(os.path.join(args.output_dir , "checkpoint-epoch=*.ckpt" ) , recursive=_UpperCamelCase ) ) __lowerCAmelCase = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(_UpperCamelCase ) if __name__ == "__main__": main()
57
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : Union[str, Any] = 3_8_4 if "tiny" in model_name: UpperCAmelCase__ : int = [3, 3, 9, 3] UpperCAmelCase__ : Union[str, Any] = [9_6, 1_9_2, 3_8_4, 7_6_8] if "small" in model_name: UpperCAmelCase__ : Optional[int] = [3, 3, 2_7, 3] UpperCAmelCase__ : Dict = [9_6, 1_9_2, 3_8_4, 7_6_8] if "base" in model_name: UpperCAmelCase__ : List[str] = [3, 3, 2_7, 3] UpperCAmelCase__ : str = [1_2_8, 2_5_6, 5_1_2, 1_0_2_4] UpperCAmelCase__ : Optional[int] = 5_1_2 if "large" in model_name: UpperCAmelCase__ : Optional[Any] = [3, 3, 2_7, 3] UpperCAmelCase__ : Optional[int] = [1_9_2, 3_8_4, 7_6_8, 1_5_3_6] UpperCAmelCase__ : Optional[int] = 7_6_8 if "xlarge" in model_name: UpperCAmelCase__ : Tuple = [3, 3, 2_7, 3] UpperCAmelCase__ : int = [2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] UpperCAmelCase__ : int = 1_0_2_4 # set label information UpperCAmelCase__ : Tuple = 1_5_0 UpperCAmelCase__ : Union[str, Any] = """huggingface/label-files""" UpperCAmelCase__ : Tuple = """ade20k-id2label.json""" UpperCAmelCase__ : Dict = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase__ : str = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} UpperCAmelCase__ : Union[str, Any] = {v: k for k, v in idalabel.items()} UpperCAmelCase__ : str = ConvNextConfig( depths=UpperCamelCase__ , hidden_sizes=UpperCamelCase__ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) UpperCAmelCase__ : Union[str, Any] = UperNetConfig( backbone_config=UpperCamelCase__ , auxiliary_in_channels=UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ , ) return config def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : str = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Tuple = dct.pop(UpperCamelCase__ ) UpperCAmelCase__ : Dict = val def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : List[str] = { """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""", """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""", """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""", """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""", """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""", } UpperCAmelCase__ : Tuple = model_name_to_url[model_name] UpperCAmelCase__ : int = torch.hub.load_state_dict_from_url(UpperCamelCase__ , map_location="""cpu""" )["""state_dict"""] UpperCAmelCase__ : int = get_upernet_config(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = UperNetForSemanticSegmentation(UpperCamelCase__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): UpperCAmelCase__ : Optional[Any] = state_dict.pop(UpperCamelCase__ ) if "bn" in key: UpperCAmelCase__ : List[str] = key.replace("""bn""" , """batch_norm""" ) UpperCAmelCase__ : List[Any] = val # rename keys UpperCAmelCase__ : Any = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify on image UpperCAmelCase__ : Optional[int] = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" UpperCAmelCase__ : Optional[Any] = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ).convert("""RGB""" ) UpperCAmelCase__ : Optional[int] = SegformerImageProcessor() UpperCAmelCase__ : Dict = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values with torch.no_grad(): UpperCAmelCase__ : Dict = model(UpperCamelCase__ ) if model_name == "upernet-convnext-tiny": UpperCAmelCase__ : Any = torch.tensor( [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]] ) elif model_name == "upernet-convnext-small": UpperCAmelCase__ : Dict = torch.tensor( [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]] ) elif model_name == "upernet-convnext-base": UpperCAmelCase__ : Optional[Any] = torch.tensor( [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]] ) elif model_name == "upernet-convnext-large": UpperCAmelCase__ : str = torch.tensor( [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]] ) elif model_name == "upernet-convnext-xlarge": UpperCAmelCase__ : List[str] = torch.tensor( [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]] ) 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 =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-convnext-tiny', type=str, choices=[f"""upernet-convnext-{size}""" for size in ['tiny', 'small', 'base', 'large', 'xlarge']], help='Name of the ConvNext UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __A =parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
163
0
"""simple docstring""" import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case__ , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(snake_case__ , "num_attention_heads" ) ) self.parent.assertTrue(hasattr(snake_case__ , "num_encoder_blocks" ) ) class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=64 , snake_case__=3 , snake_case__=4 , snake_case__=[2, 2, 2, 2] , snake_case__=[8, 4, 2, 1] , snake_case__=[16, 32, 64, 128] , snake_case__=[1, 4, 8, 16] , snake_case__=[1, 2, 4, 8] , snake_case__=True , snake_case__=True , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , ): '''simple docstring''' lowercase__ : List[str]= parent lowercase__ : Optional[int]= batch_size lowercase__ : int= image_size lowercase__ : Optional[int]= num_channels lowercase__ : str= num_encoder_blocks lowercase__ : str= sr_ratios lowercase__ : List[str]= depths lowercase__ : List[str]= hidden_sizes lowercase__ : str= downsampling_rates lowercase__ : str= num_attention_heads lowercase__ : Tuple= is_training lowercase__ : Any= use_labels lowercase__ : Any= hidden_act lowercase__ : Optional[Any]= hidden_dropout_prob lowercase__ : Tuple= attention_probs_dropout_prob lowercase__ : Dict= initializer_range lowercase__ : Union[str, Any]= num_labels lowercase__ : Dict= scope def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Dict= None if self.use_labels: lowercase__ : List[Any]= ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowercase__ : Dict= self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self ): '''simple docstring''' return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : List[Any]= SegformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[str]= model(snake_case__ ) lowercase__ : Any= self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Union[str, Any]= self.num_labels lowercase__ : Union[str, Any]= SegformerForSemanticSegmentation(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= model(snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) lowercase__ : Dict= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : str= 1 lowercase__ : List[str]= SegformerForSemanticSegmentation(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Union[str, Any]= torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(snake_case__ ) lowercase__ : Optional[Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.prepare_config_and_inputs() lowercase__, lowercase__, lowercase__ : List[str]= config_and_inputs lowercase__ : Tuple= {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) __lowerCamelCase = ( { "feature-extraction": SegformerModel, "image-classification": SegformerForImageClassification, "image-segmentation": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= SegformerModelTester(self ) lowercase__ : Optional[Any]= SegformerConfigTester(self , config_class=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*snake_case__ ) @unittest.skip("SegFormer does not use inputs_embeds" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__, lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Tuple= model_class(snake_case__ ) lowercase__ : List[str]= inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : List[str]= [*signature.parameters.keys()] lowercase__ : Optional[int]= ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__, lowercase__ : Optional[int]= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : str= True for model_class in self.all_model_classes: lowercase__ : Dict= True lowercase__ : Any= False lowercase__ : Optional[int]= True lowercase__ : Any= model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): lowercase__ : Any= model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) lowercase__ : str= outputs.attentions lowercase__ : Dict= sum(self.model_tester.depths ) self.assertEqual(len(snake_case__ ) , snake_case__ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowercase__ : Union[str, Any]= True lowercase__ : List[str]= model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): lowercase__ : List[str]= model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) lowercase__ : Tuple= outputs.attentions self.assertEqual(len(snake_case__ ) , snake_case__ ) # verify the first attentions (first block, first layer) lowercase__ : Union[str, Any]= (self.model_tester.image_size // 4) ** 2 lowercase__ : str= (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) lowercase__ : Any= (self.model_tester.image_size // 32) ** 2 lowercase__ : Union[str, Any]= (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) lowercase__ : Optional[int]= len(snake_case__ ) # Check attention is always last and order is fine lowercase__ : Optional[int]= True lowercase__ : Optional[int]= True lowercase__ : str= model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): lowercase__ : List[Any]= model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) self.assertEqual(out_len + 1 , len(snake_case__ ) ) lowercase__ : Union[str, Any]= outputs.attentions self.assertEqual(len(snake_case__ ) , snake_case__ ) # verify the first attentions (first block, first layer) lowercase__ : Optional[int]= (self.model_tester.image_size // 4) ** 2 lowercase__ : Any= (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def UpperCAmelCase_ ( self ): '''simple docstring''' def check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ): lowercase__ : str= model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): lowercase__ : str= model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) lowercase__ : int= outputs.hidden_states lowercase__ : int= self.model_tester.num_encoder_blocks self.assertEqual(len(snake_case__ ) , snake_case__ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) lowercase__, lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Tuple= True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : List[Any]= True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' if not self.model_tester.is_training: return lowercase__, lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int= True for model_class in self.all_model_classes: if model_class in get_values(snake_case__ ): continue lowercase__ : Any= model_class(snake_case__ ) model.to(snake_case__ ) model.train() lowercase__ : Any= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) lowercase__ : Dict= model(**snake_case__ ).loss loss.backward() @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : Tuple= SegformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def lowercase__() ->int: """simple docstring""" lowercase__ : List[str]= Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): '''simple docstring''' # only resize + normalize lowercase__ : Optional[int]= SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=snake_case__ , align=snake_case__ , do_random_crop=snake_case__ ) lowercase__ : Optional[Any]= SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to( snake_case__ ) lowercase__ : Any= prepare_img() lowercase__ : Dict= image_processor(images=snake_case__ , return_tensors="pt" ) lowercase__ : List[str]= encoded_inputs.pixel_values.to(snake_case__ ) with torch.no_grad(): lowercase__ : List[Any]= model(snake_case__ ) lowercase__ : Union[str, Any]= torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , snake_case__ ) lowercase__ : int= torch.tensor( [ [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ] ).to(snake_case__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' # only resize + normalize lowercase__ : List[Any]= SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=snake_case__ , align=snake_case__ , do_random_crop=snake_case__ ) lowercase__ : Tuple= SegformerForSemanticSegmentation.from_pretrained( "nvidia/segformer-b1-finetuned-cityscapes-1024-1024" ).to(snake_case__ ) lowercase__ : List[Any]= prepare_img() lowercase__ : Optional[int]= image_processor(images=snake_case__ , return_tensors="pt" ) lowercase__ : Optional[Any]= encoded_inputs.pixel_values.to(snake_case__ ) with torch.no_grad(): lowercase__ : Union[str, Any]= model(snake_case__ ) lowercase__ : str= torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , snake_case__ ) lowercase__ : Union[str, Any]= torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]], ] ).to(snake_case__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , snake_case__ , atol=1e-1 ) ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' # only resize + normalize lowercase__ : str= SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=snake_case__ , align=snake_case__ , do_random_crop=snake_case__ ) lowercase__ : Dict= SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to( snake_case__ ) lowercase__ : int= prepare_img() lowercase__ : Union[str, Any]= image_processor(images=snake_case__ , return_tensors="pt" ) lowercase__ : Tuple= encoded_inputs.pixel_values.to(snake_case__ ) with torch.no_grad(): lowercase__ : int= model(snake_case__ ) lowercase__ : Tuple= outputs.logits.detach().cpu() lowercase__ : Union[str, Any]= image_processor.post_process_semantic_segmentation(outputs=snake_case__ , target_sizes=[(500, 300)] ) lowercase__ : Optional[Any]= torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , snake_case__ ) lowercase__ : str= image_processor.post_process_semantic_segmentation(outputs=snake_case__ ) lowercase__ : str= torch.Size((128, 128) ) self.assertEqual(segmentation[0].shape , snake_case__ )
150
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() a : List[str] = logging.get_logger(__name__) a : List[Any] = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] a : Dict = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowercase__(A ) ->Optional[int]: """simple docstring""" lowercase__ : Any= torch.load(A , map_location="cpu" ) return sd def lowercase__(A , A , A=rename_keys_prefix ) ->List[str]: """simple docstring""" lowercase__ : int= OrderedDict() lowercase__ : Optional[Any]= torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue lowercase__ : Union[str, Any]= key for name_pair in rename_keys_prefix: lowercase__ : str= new_key.replace(name_pair[0] , name_pair[1] ) lowercase__ : Union[str, Any]= d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately lowercase__ : Optional[int]= new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowercase__(A , A ) ->str: """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: lowercase__ : Union[str, Any]= "pretraining" if "vcr" in checkpoint_path: lowercase__ : str= {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: lowercase__ : Optional[Any]= {"visual_embedding_dim": 2_048} elif "vqa" in checkpoint_path: lowercase__ : int= {"visual_embedding_dim": 2_048} elif "nlvr" in checkpoint_path: lowercase__ : Tuple= {"visual_embedding_dim": 1_024} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: lowercase__ : int= {"visual_embedding_dim": 512} lowercase__ : int= "multichoice" elif "vqa_advanced" in checkpoint_path: lowercase__ : Dict= {"visual_embedding_dim": 2_048} lowercase__ : Optional[Any]= "vqa_advanced" elif "vqa" in checkpoint_path: lowercase__ : Optional[int]= {"visual_embedding_dim": 2_048, "num_labels": 3_129} lowercase__ : List[str]= "vqa" elif "nlvr" in checkpoint_path: lowercase__ : Dict= { "visual_embedding_dim": 1_024, "num_labels": 2, } lowercase__ : Any= "nlvr" lowercase__ : List[Any]= VisualBertConfig(**A ) # Load State Dict lowercase__ : Union[str, Any]= load_state_dict(A ) lowercase__ : List[str]= get_new_dict(A , A ) if model_type == "pretraining": lowercase__ : Optional[Any]= VisualBertForPreTraining(A ) elif model_type == "vqa": lowercase__ : Any= VisualBertForQuestionAnswering(A ) elif model_type == "nlvr": lowercase__ : Union[str, Any]= VisualBertForVisualReasoning(A ) elif model_type == "multichoice": lowercase__ : str= VisualBertForMultipleChoice(A ) model.load_state_dict(A ) # Save Checkpoints Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) if __name__ == "__main__": a : int = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") a : Dict = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
150
1
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants _UpperCamelCase = Mapping[str, np.ndarray] _UpperCamelCase = Mapping[str, Any] # Is a nested dict. _UpperCamelCase = 0.01 @dataclasses.dataclass(frozen=_UpperCAmelCase ) class __lowercase : _UpperCamelCase = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. _UpperCamelCase = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. _UpperCamelCase = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. _UpperCamelCase = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. _UpperCamelCase = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions _UpperCamelCase = None # Optional remark about the protein. Included as a comment in output PDB # files _UpperCamelCase = None # Templates used to generate this protein (prediction-only) _UpperCamelCase = None # Chain corresponding to each parent _UpperCamelCase = None def _lowercase ( lowercase__ ): __lowerCAmelCase : Optional[int] = r'''(\[[A-Z]+\]\n)''' __lowerCAmelCase : List[str] = [tag.strip() for tag in re.split(lowercase__ , lowercase__ ) if len(lowercase__ ) > 0] __lowerCAmelCase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) __lowerCAmelCase : List[str] = ["N", "CA", "C"] __lowerCAmelCase : Dict = None __lowerCAmelCase : List[str] = None __lowerCAmelCase : int = None for g in groups: if "[PRIMARY]" == g[0]: __lowerCAmelCase : Optional[Any] = g[1][0].strip() for i in range(len(lowercase__ ) ): if seq[i] not in residue_constants.restypes: __lowerCAmelCase : Any = '''X''' # FIXME: strings are immutable __lowerCAmelCase : str = np.array( [residue_constants.restype_order.get(lowercase__ , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __lowerCAmelCase : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(lowercase__ , g[1][axis].split() ) ) ) __lowerCAmelCase : List[str] = np.array(lowercase__ ) __lowerCAmelCase : str = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(lowercase__ ): __lowerCAmelCase : str = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __lowerCAmelCase : Optional[int] = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) __lowerCAmelCase : Union[str, Any] = np.zeros( ( len(lowercase__ ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(lowercase__ ): __lowerCAmelCase : List[Any] = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=lowercase__ , atom_mask=lowercase__ , aatype=lowercase__ , residue_index=np.arange(len(lowercase__ ) ) , b_factors=lowercase__ , ) def _lowercase ( lowercase__ , lowercase__ = 0 ): __lowerCAmelCase : List[str] = [] __lowerCAmelCase : Tuple = prot.remark if remark is not None: pdb_headers.append(f"""REMARK {remark}""" ) __lowerCAmelCase : Optional[Any] = prot.parents __lowerCAmelCase : Tuple = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __lowerCAmelCase : List[str] = [p for i, p in zip(lowercase__ , lowercase__ ) if i == chain_id] if parents is None or len(lowercase__ ) == 0: __lowerCAmelCase : Dict = ['''N/A'''] pdb_headers.append(f"""PARENT {" ".join(lowercase__ )}""" ) return pdb_headers def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = [] __lowerCAmelCase : str = pdb_str.split('''\n''' ) __lowerCAmelCase : Union[str, Any] = prot.remark if remark is not None: out_pdb_lines.append(f"""REMARK {remark}""" ) __lowerCAmelCase : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: __lowerCAmelCase : Tuple = [] if prot.parents_chain_index is not None: __lowerCAmelCase : Dict[str, List[str]] = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(lowercase__ ) , [] ) parent_dict[str(lowercase__ )].append(lowercase__ ) __lowerCAmelCase : int = max([int(lowercase__ ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __lowerCAmelCase : Dict = parent_dict.get(str(lowercase__ ) , ['''N/A'''] ) parents_per_chain.append(lowercase__ ) else: parents_per_chain.append(list(prot.parents ) ) else: __lowerCAmelCase : Union[str, Any] = [['''N/A''']] def make_parent_line(lowercase__ ) -> str: return f"""PARENT {" ".join(lowercase__ )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __lowerCAmelCase : Optional[Any] = 0 for i, l in enumerate(lowercase__ ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(lowercase__ ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(lowercase__ ): __lowerCAmelCase : Tuple = parents_per_chain[chain_counter] else: __lowerCAmelCase : Tuple = ['''N/A'''] out_pdb_lines.append(make_parent_line(lowercase__ ) ) return "\n".join(lowercase__ ) def _lowercase ( lowercase__ ): __lowerCAmelCase : Union[str, Any] = residue_constants.restypes + ['''X'''] def res_atoa(lowercase__ ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) __lowerCAmelCase : Tuple = residue_constants.atom_types __lowerCAmelCase : List[str] = [] __lowerCAmelCase : Any = prot.atom_mask __lowerCAmelCase : Dict = prot.aatype __lowerCAmelCase : Any = prot.atom_positions __lowerCAmelCase : List[Any] = prot.residue_index.astype(np.intaa ) __lowerCAmelCase : int = prot.b_factors __lowerCAmelCase : Any = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) __lowerCAmelCase : Optional[Any] = get_pdb_headers(lowercase__ ) if len(lowercase__ ) > 0: pdb_lines.extend(lowercase__ ) __lowerCAmelCase : Optional[int] = aatype.shape[0] __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Union[str, Any] = string.ascii_uppercase __lowerCAmelCase : List[str] = None # Add all atom sites. for i in range(lowercase__ ): __lowerCAmelCase : Any = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(lowercase__ , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue __lowerCAmelCase : Optional[int] = '''ATOM''' __lowerCAmelCase : List[str] = atom_name if len(lowercase__ ) == 4 else f""" {atom_name}""" __lowerCAmelCase : List[Any] = '''''' __lowerCAmelCase : Optional[Any] = '''''' __lowerCAmelCase : Optional[int] = 1.0_0 __lowerCAmelCase : List[Any] = atom_name[0] # Protein supports only C, N, O, S, this works. __lowerCAmelCase : List[Any] = '''''' __lowerCAmelCase : Tuple = '''A''' if chain_index is not None: __lowerCAmelCase : int = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __lowerCAmelCase : Union[str, Any] = ( f"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" f"""{res_name_a:>3} {chain_tag:>1}""" f"""{residue_index[i]:>4}{insertion_code:>1} """ f"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" f"""{occupancy:>6.2f}{b_factor:>6.2f} """ f"""{element:>2}{charge:>2}""" ) pdb_lines.append(lowercase__ ) atom_index += 1 __lowerCAmelCase : str = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __lowerCAmelCase : Union[str, Any] = True __lowerCAmelCase : Optional[Any] = chain_index[i + 1] if should_terminate: # Close the chain. __lowerCAmelCase : Tuple = '''TER''' __lowerCAmelCase : Optional[int] = ( f"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(lowercase__ ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(lowercase__ , lowercase__ ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(lowercase__ ) def _lowercase ( lowercase__ ): return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _lowercase ( lowercase__ , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , ): return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=lowercase__ , remark=lowercase__ , parents=lowercase__ , parents_chain_index=lowercase__ , )
275
def _lowercase ( lowercase__ , lowercase__ ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
275
1
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : str = GPTSanJapaneseTokenizer UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : Dict = {"""do_clean_text""": False, """add_prefix_space""": False} def _snake_case ( self : Any ) -> str: '''simple docstring''' super().setUp() # fmt: off A: Optional[Any] = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on A: Union[str, Any] = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 A: Union[str, Any] = {'''unk_token''': '''<unk>'''} A: Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : Optional[int] , **SCREAMING_SNAKE_CASE_ : str ) -> List[Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' A: Union[str, Any] = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]: '''simple docstring''' A , A: int = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Optional[int] = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def _snake_case ( self : int ) -> Optional[Any]: '''simple docstring''' pass # TODO add if relevant def _snake_case ( self : Optional[Any] ) -> Dict: '''simple docstring''' pass # TODO add if relevant def _snake_case ( self : List[str] ) -> str: '''simple docstring''' pass # TODO add if relevant def _snake_case ( self : int ) -> str: '''simple docstring''' A: Optional[Any] = self.get_tokenizer() # Testing tokenization A: Dict = '''こんにちは、世界。 こんばんは、㔺界。''' A: str = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] A: str = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens A: int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] A: Any = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens A: int = tokens + [tokenizer.unk_token] A: int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] A: List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Any ) -> List[Any]: '''simple docstring''' A: Tuple = self.get_tokenizer() # Testing tokenization A: List[str] = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' A: Tuple = '''こんにちは、、、、世界。こんばんは、、、、世界。''' A: str = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : str ) -> List[str]: '''simple docstring''' A: List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization A: Optional[int] = '''こんにちは、世界。''' A: str = '''こんばんは、㔺界。😀''' A: str = '''こんにちは、世界。こんばんは、世界。😀''' A: Optional[Any] = tokenizer.encode(prefix_text + input_text ) A: Dict = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) A: str = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) A: Optional[int] = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) A: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : List[Any] ) -> Dict: '''simple docstring''' A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization A: Tuple = '''こんにちは、世界。''' A: List[Any] = '''こんばんは、㔺界。😀''' A: int = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 A: str = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 A: List[Any] = [1] + [0] * (len_prefix + len_text + 1) A: Any = [1] * (len_prefix + len_text + 1) + [0] A: Optional[Any] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) A: Tuple = tokenizer(prefix_text + input_text ).token_type_ids A: int = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids A: List[str] = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' A: Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) A: Dict = tokenizer.encode('''あンいワ''' ) A: str = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) A: Dict = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def _snake_case ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) A: List[Any] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] A: Tuple = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: str = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off A: Optional[Any] = [[3_59_93, 86_40, 2_59_48, 3_59_98, 3_06_47, 3_56_75, 3_59_99, 3_59_99], [3_59_93, 1_03_82, 98_68, 3_59_98, 3_06_46, 94_59, 3_06_46, 3_56_75]] A: Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] A: List[str] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Any ) -> Dict: '''simple docstring''' pass def _snake_case ( self : int ) -> List[Any]: '''simple docstring''' pass
334
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _A = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from math import ceil, sqrt def _lowerCAmelCase ( __lowerCAmelCase = 1000000 ) -> int: """simple docstring""" snake_case__ : Dict = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: snake_case__ : Any = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: snake_case__ : int = 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() = }""")
230
0
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # noqa: E741 __lowerCAmelCase: Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Tuple = 0 __lowerCAmelCase: List[Any] = [0] * n __lowerCAmelCase: Tuple = [False] * n __lowerCAmelCase: Optional[Any] = [False] * n def dfs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if parent == root: out_edge_count += 1 __lowerCAmelCase: List[Any] = True __lowerCAmelCase: Optional[int] = at for to in l[at]: if to == parent: pass elif not visited[to]: __lowerCAmelCase: Dict = dfs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Optional[Any] = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: __lowerCAmelCase: List[str] = True # AP found via cycle if at == low[to]: __lowerCAmelCase: Optional[int] = True else: __lowerCAmelCase: Optional[Any] = min(low[at] , __SCREAMING_SNAKE_CASE ) return out_edge_count for i in range(__SCREAMING_SNAKE_CASE ): if not visited[i]: __lowerCAmelCase: List[str] = 0 __lowerCAmelCase: Any = dfs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , -1 , __SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Any = out_edge_count > 1 for x in range(len(__SCREAMING_SNAKE_CASE ) ): if is_art[x] is True: print(__SCREAMING_SNAKE_CASE ) # Adjacency list of graph __A = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
356
"""simple docstring""" from __future__ import annotations from math import pi def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> dict[str, float]: if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
108
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __A ( metaclass=UpperCamelCase__ ): a__ : List[str] = ["""onnx"""] def __init__(self : List[Any] , *__a : Dict , **__a : Optional[Any] ): requires_backends(self , ["onnx"] ) @classmethod def _lowercase (cls : List[str] , *__a : Any , **__a : List[Any] ): requires_backends(cls , ["onnx"] ) @classmethod def _lowercase (cls : Optional[int] , *__a : Any , **__a : int ): requires_backends(cls , ["onnx"] )
1
'''simple docstring''' import math def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase_ = input("Enter message: " ) UpperCAmelCase_ = int(input(f"""Enter key [2-{len(snake_case_ ) - 1}]: """ ) ) UpperCAmelCase_ = input("Encryption/Decryption [e/d]: " ) if mode.lower().startswith("e" ): UpperCAmelCase_ = encrypt_message(snake_case_ , snake_case_ ) elif mode.lower().startswith("d" ): UpperCAmelCase_ = decrypt_message(snake_case_ , snake_case_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"""Output:\n{text + "|"}""" ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : str ) -> str: '''simple docstring''' UpperCAmelCase_ = [""] * key for col in range(snake_case_ ): UpperCAmelCase_ = col while pointer < len(snake_case_ ): cipher_text[col] += message[pointer] pointer += key return "".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : str ) -> str: '''simple docstring''' UpperCAmelCase_ = math.ceil(len(snake_case_ ) / key ) UpperCAmelCase_ = key UpperCAmelCase_ = (num_cols * num_rows) - len(snake_case_ ) UpperCAmelCase_ = [""] * num_cols UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): UpperCAmelCase_ = 0 row += 1 return "".join(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
1
1
'''simple docstring''' import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> Optional[int]: '''simple docstring''' return x + 2 class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" snake_case : Optional[Any] = '''x = 3''' snake_case : List[str] = {} snake_case : Union[str, Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3} ) snake_case : int = '''x = y''' snake_case : str = {'''y''': 5} snake_case : str = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 5, '''y''': 5} ) def lowerCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" snake_case : Optional[int] = '''y = add_two(x)''' snake_case : Optional[int] = {'''x''': 3} snake_case : Any = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) # Won't work without the tool with CaptureStdout() as out: snake_case : Union[str, Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result is None assert "tried to execute add_two" in out.out def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" snake_case : Union[str, Any] = '''x = 3''' snake_case : Tuple = {} snake_case : Optional[Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3} ) def lowerCAmelCase ( self : Union[str, Any] ) -> int: """simple docstring""" snake_case : Optional[Any] = '''test_dict = {\'x\': x, \'y\': add_two(x)}''' snake_case : Tuple = {'''x''': 3} snake_case : int = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def lowerCAmelCase ( self : Union[str, Any] ) -> int: """simple docstring""" snake_case : Optional[int] = '''x = 3\ny = 5''' snake_case : List[Any] = {} snake_case : Dict = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) def lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" snake_case : Any = '''text = f\'This is x: {x}.\'''' snake_case : Any = {'''x''': 3} snake_case : Dict = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''text''': '''This is x: 3.'''} ) def lowerCAmelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" snake_case : Union[str, Any] = '''if x <= 3:\n y = 2\nelse:\n y = 5''' snake_case : List[str] = {'''x''': 3} snake_case : Dict = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 2} ) snake_case : List[str] = {'''x''': 8} snake_case : int = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 8, '''y''': 5} ) def lowerCAmelCase ( self : str ) -> List[Any]: """simple docstring""" snake_case : str = '''test_list = [x, add_two(x)]''' snake_case : Dict = {'''x''': 3} snake_case : str = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , [3, 5] ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_list''': [3, 5]} ) def lowerCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" snake_case : List[Any] = '''y = x''' snake_case : List[Any] = {'''x''': 3} snake_case : Dict = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 3} ) def lowerCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" snake_case : Dict = '''test_list = [x, add_two(x)]\ntest_list[1]''' snake_case : int = {'''x''': 3} snake_case : Tuple = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_list''': [3, 5]} ) snake_case : int = '''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']''' snake_case : Any = {'''x''': 3} snake_case : str = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def lowerCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" snake_case : Any = '''x = 0\nfor i in range(3):\n x = i''' snake_case : Optional[int] = {} snake_case : Tuple = evaluate(UpperCamelCase__ , {'''range''': range} , state=UpperCamelCase__ ) assert result == 2 self.assertDictEqual(UpperCamelCase__ , {'''x''': 2, '''i''': 2} )
83
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str]=3 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Any=[10, 20, 30, 40] , UpperCamelCase__ : Any=[1, 1, 2, 1] , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str="relu" , UpperCamelCase__ : Union[str, Any]=3 , UpperCamelCase__ : Tuple=None , ) -> List[str]: """simple docstring""" snake_case : List[str] = parent snake_case : Tuple = batch_size snake_case : int = image_size snake_case : Any = num_channels snake_case : Optional[int] = embeddings_size snake_case : Optional[int] = hidden_sizes snake_case : str = depths snake_case : Tuple = is_training snake_case : List[str] = use_labels snake_case : List[str] = hidden_act snake_case : Tuple = num_labels snake_case : Tuple = scope snake_case : List[str] = len(UpperCamelCase__ ) def lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case : Any = self.get_config() return config, pixel_values def lowerCAmelCase ( self : List[str] ) -> str: """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 , image_size=self.image_size , ) def lowerCAmelCase ( self : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int ) -> Tuple: """simple docstring""" snake_case : List[str] = FlaxRegNetModel(config=UpperCamelCase__ ) snake_case : str = model(UpperCamelCase__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : Dict , UpperCamelCase__ : Any , UpperCamelCase__ : Dict ) -> Dict: """simple docstring""" snake_case : int = self.num_labels snake_case : List[str] = FlaxRegNetForImageClassification(config=UpperCamelCase__ ) snake_case : Any = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" snake_case : str = self.prepare_config_and_inputs() snake_case ,snake_case : Tuple = config_and_inputs snake_case : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class snake_case__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" lowerCamelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def lowerCAmelCase ( self : List[str] ) -> None: """simple docstring""" snake_case : List[str] = FlaxRegNetModelTester(self ) snake_case : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCAmelCase ( self : Any ) -> str: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : Tuple ) -> Any: """simple docstring""" return def lowerCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def lowerCAmelCase ( self : List[str] ) -> int: """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def lowerCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" pass def lowerCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" snake_case ,snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Union[str, Any] = model_class(UpperCamelCase__ ) snake_case : Union[str, Any] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : int = [*signature.parameters.keys()] snake_case : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" def check_hidden_states_output(UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple ): snake_case : Union[str, Any] = model_class(UpperCamelCase__ ) snake_case : Any = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) snake_case : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case : Optional[int] = self.model_tester.num_stages self.assertEqual(len(UpperCamelCase__ ) , expected_num_stages + 1 ) snake_case ,snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Tuple = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case : List[str] = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" snake_case ,snake_case : str = 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 : Any = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) snake_case : Optional[Any] = model_class(UpperCamelCase__ ) @jax.jit def model_jitted(UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ): return model(pixel_values=UpperCamelCase__ , **UpperCamelCase__ ) with self.subTest('''JIT Enabled''' ): snake_case : Optional[int] = model_jitted(**UpperCamelCase__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): snake_case : Tuple = model_jitted(**UpperCamelCase__ ).to_tuple() self.assertEqual(len(UpperCamelCase__ ) , len(UpperCamelCase__ ) ) for jitted_output, output in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def _UpperCamelCase ( ) -> Union[str, Any]: '''simple docstring''' snake_case : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class snake_case__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCAmelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def lowerCAmelCase ( self : int ) -> int: """simple docstring""" snake_case : str = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) snake_case : Any = self.default_image_processor snake_case : Any = prepare_img() snake_case : Union[str, Any] = image_processor(images=UpperCamelCase__ , return_tensors='''np''' ) snake_case : List[str] = model(**UpperCamelCase__ ) # verify the logits snake_case : Optional[int] = (1, 1000) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) snake_case : Dict = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) )
83
1
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a ( _lowerCamelCase , unittest.TestCase ): snake_case_ = LayoutLMTokenizer snake_case_ = LayoutLMTokenizerFast snake_case_ = True snake_case_ = True def A_ ( self : Optional[Any] ): super().setUp() snake_case_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case_ = 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 : Any , **lowercase_ : Optional[Any] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **lowercase_ ) def A_ ( self : Union[str, Any] , lowercase_ : Optional[int] ): snake_case_ = '''UNwant\u00E9d,running''' snake_case_ = '''unwanted, running''' return input_text, output_text def A_ ( self : Dict ): snake_case_ = self.tokenizer_class(self.vocab_file ) snake_case_ = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(lowercase_ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ) , [7, 4, 5, 10, 8, 9] ) def A_ ( self : Any ): pass
56
from __future__ import annotations lowercase__ : str = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): '''simple docstring''' snake_case_ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_A ) ) ] # the reference grid snake_case_ = 1 snake_case_ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_A ) ) ] # the action grid snake_case_ = init[0] snake_case_ = init[1] snake_case_ = 0 snake_case_ = g + heuristic[x][y] # cost from starting cell to destination cell snake_case_ = [[f, g, x, y]] snake_case_ = False # flag that is set when search is complete snake_case_ = False # flag set if we can't find expand while not found and not resign: if len(_A ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() snake_case_ = cell.pop() snake_case_ = next_cell[2] snake_case_ = next_cell[3] snake_case_ = next_cell[1] if x == goal[0] and y == goal[1]: snake_case_ = True else: for i in range(len(_A ) ): # to try out different valid actions snake_case_ = x + DIRECTIONS[i][0] snake_case_ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(_A ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: snake_case_ = g + cost snake_case_ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) snake_case_ = 1 snake_case_ = i snake_case_ = [] snake_case_ = goal[0] snake_case_ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: snake_case_ = x - DIRECTIONS[action[x][y]][0] snake_case_ = y - DIRECTIONS[action[x][y]][1] snake_case_ = xa snake_case_ = ya invpath.append([x, y] ) snake_case_ = [] for i in range(len(_A ) ): path.append(invpath[len(_A ) - 1 - i] ) return path, action if __name__ == "__main__": lowercase__ : Union[str, Any] = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] lowercase__ : Optional[Any] = [0, 0] # all coordinates are given in format [y,x] lowercase__ : Tuple = [len(grid) - 1, len(grid[0]) - 1] lowercase__ : Dict = 1 # the cost map which pushes the path closer to the goal lowercase__ : Any = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): lowercase__ : Union[str, Any] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map lowercase__ : int = 99 lowercase__ , lowercase__ : Tuple = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
187
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel snake_case : Tuple = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } snake_case : Dict = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def __lowerCamelCase ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str=False ): """simple docstring""" a , a :str = create_model( '''HTSAT-tiny''' , '''roberta''' , UpperCAmelCase_ , precision='''fp32''' , device='''cuda:0''' if torch.cuda.is_available() else '''cpu''' , enable_fusion=UpperCAmelCase_ , fusion_type='''aff_2d''' if enable_fusion else None , ) return model, model_cfg def __lowerCamelCase ( UpperCAmelCase_ : Optional[Any] ): """simple docstring""" a :Dict = {} a :List[Any] = R'''.*sequential.(\d+).*''' a :List[str] = R'''.*_projection.(\d+).*''' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: a :int = key.replace(UpperCAmelCase_ , UpperCAmelCase_ ) if re.match(UpperCAmelCase_ , UpperCAmelCase_ ): # replace sequential layers with list a :Dict = re.match(UpperCAmelCase_ , UpperCAmelCase_ ).group(1 ) a :Any = key.replace(F'''sequential.{sequential_layer}.''' , F'''layers.{int(UpperCAmelCase_ )//3}.linear.''' ) elif re.match(UpperCAmelCase_ , UpperCAmelCase_ ): a :Tuple = int(re.match(UpperCAmelCase_ , UpperCAmelCase_ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... a :str = 1 if projecton_layer == 0 else 2 a :int = key.replace(F'''_projection.{projecton_layer}.''' , F'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value a :Optional[Any] = value a :Any = mixed_qkv.size(0 ) // 3 a :int = mixed_qkv[:qkv_dim] a :Any = mixed_qkv[qkv_dim : qkv_dim * 2] a :List[Any] = mixed_qkv[qkv_dim * 2 :] a :Union[str, Any] = query_layer a :int = key_layer a :Optional[Any] = value_layer else: a :Optional[int] = value return model_state_dict def __lowerCamelCase ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : int=False ): """simple docstring""" a , a :Tuple = init_clap(UpperCAmelCase_ , enable_fusion=UpperCAmelCase_ ) clap_model.eval() a :Tuple = clap_model.state_dict() a :List[Any] = rename_state_dict(UpperCAmelCase_ ) a :Any = ClapConfig() a :Optional[int] = enable_fusion a :List[Any] = ClapModel(UpperCAmelCase_ ) # ignore the spectrogram embedding layer model.load_state_dict(UpperCAmelCase_ , strict=UpperCAmelCase_ ) model.save_pretrained(UpperCAmelCase_ ) transformers_config.save_pretrained(UpperCAmelCase_ ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') snake_case : Any = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
281
def __lowerCamelCase ( UpperCAmelCase_ : str ): """simple docstring""" if n_term == "": return [] a :list = [] for temp in range(int(UpperCAmelCase_ ) ): series.append(F'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": snake_case : Tuple = input('''Enter the last number (nth term) of the Harmonic Series''') print('''Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n''') print(harmonic_series(nth_term))
281
1
'''simple docstring''' class a__ : def __init__( self , _UpperCamelCase ): """simple docstring""" _lowercase : Tuple = n _lowercase : Any = [None] * self.n _lowercase : Tuple = 0 # index of the first element _lowercase : Union[str, Any] = 0 _lowercase : str = 0 def __len__( self ): """simple docstring""" return self.size def _lowerCamelCase ( self ): """simple docstring""" return self.size == 0 def _lowerCamelCase ( self ): """simple docstring""" return False if self.is_empty() else self.array[self.front] def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if self.size >= self.n: raise Exception("QUEUE IS FULL" ) _lowercase : Optional[int] = data _lowercase : Dict = (self.rear + 1) % self.n self.size += 1 return self def _lowerCamelCase ( self ): """simple docstring""" if self.size == 0: raise Exception("UNDERFLOW" ) _lowercase : Optional[Any] = self.array[self.front] _lowercase : List[Any] = None _lowercase : int = (self.front + 1) % self.n self.size -= 1 return temp
250
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration _snake_case = pytest.mark.integration _snake_case = {'comet'} _snake_case = importlib.util.find_spec('fairseq') is not None _snake_case = {'code_eval'} _snake_case = os.name == 'nt' _snake_case = {'bertscore', 'frugalscore', 'perplexity'} _snake_case = importlib.util.find_spec('transformers') is not None def _A ( snake_case ) -> Tuple: @wraps(snake_case ) def wrapper(self , snake_case ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , snake_case ) return wrapper def _A ( snake_case ) -> Optional[int]: @wraps(snake_case ) def wrapper(self , snake_case ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , snake_case ) return wrapper def _A ( snake_case ) -> List[Any]: @wraps(snake_case ) def wrapper(self , snake_case ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , snake_case ) return wrapper def _A ( ) -> List[Any]: _lowercase : Any = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) @local class a__ ( parameterized.TestCase ): _SCREAMING_SNAKE_CASE : Any = {} _SCREAMING_SNAKE_CASE : Any = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Tuple = "[...]" _lowercase : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , _UpperCamelCase ) ).module_path ) _lowercase : Union[str, Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=_UpperCamelCase ) # check parameters _lowercase : str = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(_UpperCamelCase , metric_module.__name__ ): with self.use_local_metrics(): try: _lowercase : int = doctest.testmod(_UpperCamelCase , verbose=_UpperCamelCase , raise_on_error=_UpperCamelCase ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Any = "[...]" _lowercase : Dict = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , _UpperCamelCase ) ).module_path ) # run doctest with self.use_local_metrics(): _lowercase : str = doctest.testmod(_UpperCamelCase , verbose=_UpperCamelCase , raise_on_error=_UpperCamelCase ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](_UpperCamelCase ): yield else: yield @contextmanager def _lowerCamelCase ( self ): """simple docstring""" def load_local_metric(_UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ): return load_metric(os.path.join("metrics" , _UpperCamelCase ) , *_UpperCamelCase , **_UpperCamelCase ) with patch("datasets.load_metric" ) as mock_load_metric: _lowercase : List[Any] = load_local_metric yield @classmethod def _lowerCamelCase ( cls , _UpperCamelCase ): """simple docstring""" def wrapper(_UpperCamelCase ): _lowercase : str = contextmanager(_UpperCamelCase ) _lowercase : Any = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def _A ( snake_case ) -> List[Any]: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class a__ ( lowerCamelCase_ ): def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.0_3, 1.0_4] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: _lowercase : List[Any] = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def _A ( snake_case ) -> Tuple: import torch def bert_cos_score_idf(snake_case , snake_case , *snake_case , **snake_case ): return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: _lowercase : List[str] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def _A ( snake_case ) -> Optional[int]: def load_from_checkpoint(snake_case ): class a__ : def _lowerCamelCase ( self , _UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" assert len(_UpperCamelCase ) == 2 _lowercase : Tuple = [0.1_9, 0.9_2] return scores, sum(_UpperCamelCase ) / len(_UpperCamelCase ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: _lowercase : Union[str, Any] = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: _lowercase : str = load_from_checkpoint yield def _A ( ) -> Optional[Any]: _lowercase : str = load_metric(os.path.join("metrics" , "seqeval" ) ) _lowercase : Optional[int] = "ERROR" _lowercase : Any = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(snake_case , match=re.escape(snake_case ) ): metric.compute(predictions=[] , references=[] , scheme=snake_case )
250
1
"""simple docstring""" from datetime import datetime import requests def __lowerCAmelCase ( lowercase : List[Any] ) -> bytes: """simple docstring""" snake_case : Dict = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' snake_case : Tuple = requests.get(base_url + url ).json()[0]['urls'][0]['src'] return requests.get(lowerCAmelCase_ ).content if __name__ == "__main__": __snake_case = input("""Enter Video/IGTV url: """).strip() __snake_case = F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, """wb""") as fp: fp.write(download_video(url)) print(F'''Done. Video saved to disk as {file_name}.''')
369
"""simple docstring""" import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCAmelCase ( unittest.TestCase ): @property def lowerCamelCase ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def lowerCamelCase ( self ) -> Any: '''simple docstring''' snake_case : Any = self.dummy_uncond_unet snake_case : Tuple = KarrasVeScheduler() snake_case : int = KarrasVePipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Optional[Any] = torch.manual_seed(0 ) snake_case : List[Any] = pipe(num_inference_steps=2 , generator=UpperCamelCase__ , output_type="numpy" ).images snake_case : Dict = torch.manual_seed(0 ) snake_case : Dict = pipe(num_inference_steps=2 , generator=UpperCamelCase__ , output_type="numpy" , return_dict=UpperCamelCase__ )[0] snake_case : Tuple = image[0, -3:, -3:, -1] snake_case : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case : int = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class _lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' snake_case : Optional[Any] = "google/ncsnpp-celebahq-256" snake_case : List[str] = UNetaDModel.from_pretrained(UpperCamelCase__ ) snake_case : Optional[Any] = KarrasVeScheduler() snake_case : Optional[int] = KarrasVePipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Dict = torch.manual_seed(0 ) snake_case : Union[str, Any] = pipe(num_inference_steps=20 , generator=UpperCamelCase__ , output_type="numpy" ).images snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) snake_case : Any = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
112
0
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __SCREAMING_SNAKE_CASE : snake_case_ = None def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : int =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Tuple =json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __lowercase ) def __magic_name__ ( self : str ) -> int: SCREAMING_SNAKE_CASE__ : int =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Dict =os.path.join(__lowercase , '''feat_extract.json''' ) feat_extract_first.to_json_file(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =self.feature_extraction_class.from_json_file(__lowercase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : int =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Optional[int] =feat_extract_first.save_pretrained(__lowercase )[0] check_json_file_has_correct_format(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =self.feature_extraction_class.from_pretrained(__lowercase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def __magic_name__ ( self : Tuple ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.feature_extraction_class() self.assertIsNotNone(__lowercase )
152
'''simple docstring''' import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def _a( UpperCamelCase__ : str, UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] =AlbertConfig.from_json_file(UpperCamelCase__ ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE__ : Any =AlbertForPreTraining(UpperCamelCase__ ) # Load weights from tf checkpoint load_tf_weights_in_albert(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict(), UpperCamelCase__ ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--albert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained ALBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
152
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class __lowerCAmelCase ( unittest.TestCase ): @require_torch def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = pipeline( task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused' ) __UpperCamelCase = load_dataset('ashraq/esc50' ) __UpperCamelCase = dataset['train']['audio'][-1]['array'] __UpperCamelCase = audio_classifier(__UpperCAmelCase , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{'score': 0.5_0_1, 'label': 'Sound of a dog'}, {'score': 0.4_9_9, 'label': 'Sound of vaccum cleaner'}] , ) @unittest.skip('No models are available in TF' ) def UpperCAmelCase ( self ): '''simple docstring''' pass @slow @require_torch def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = pipeline( task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , ) # This is an audio of a dog __UpperCamelCase = load_dataset('ashraq/esc50' ) __UpperCamelCase = dataset['train']['audio'][-1]['array'] __UpperCamelCase = audio_classifier(__UpperCAmelCase , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ] , ) __UpperCamelCase = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) __UpperCamelCase = audio_classifier( [audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) @unittest.skip('No models are available in TF' ) def UpperCAmelCase ( self ): '''simple docstring''' pass
263
"""simple docstring""" def A ( snake_case :list[list[int]] , snake_case :int , snake_case :int , snake_case :list[int] ) -> bool: # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def A ( snake_case :list[list[int]] , snake_case :list[int] , snake_case :int ) -> bool: # Base Case if curr_ind == len(snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(snake_case ) ): if valid_connection(snake_case , snake_case , snake_case , snake_case ): # Insert current vertex into path as next transition __UpperCamelCase = next_ver # Validate created path if util_hamilton_cycle(snake_case , snake_case , curr_ind + 1 ): return True # Backtrack __UpperCamelCase = -1 return False def A ( snake_case :list[list[int]] , snake_case :int = 0 ) -> list[int]: __UpperCamelCase = [-1] * (len(snake_case ) + 1) # initialize start and end of path with starting index __UpperCamelCase = __UpperCamelCase = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(snake_case , snake_case , 1 ) else []
263
1
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def a__ ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
108
"""simple docstring""" from __future__ import annotations import math class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , snake_case__ ): """simple docstring""" lowerCAmelCase : Any = size # approximate the overall size of segment tree with given value lowerCAmelCase : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update lowerCAmelCase : List[str] = [0 for i in range(0 , 4 * size )] lowerCAmelCase : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase__ ( self , snake_case__ ): """simple docstring""" return idx * 2 def lowercase__ ( self , snake_case__ ): """simple docstring""" return idx * 2 + 1 def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" if left_element == right_element: lowerCAmelCase : List[str] = a[left_element - 1] else: lowerCAmelCase : Tuple = (left_element + right_element) // 2 self.build(self.left(snake_case__ ) , snake_case__ , snake_case__ , snake_case__ ) self.build(self.right(snake_case__ ) , mid + 1 , snake_case__ , snake_case__ ) lowerCAmelCase : Tuple = max( self.segment_tree[self.left(snake_case__ )] , self.segment_tree[self.right(snake_case__ )] ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" if self.flag[idx] is True: lowerCAmelCase : Optional[int] = self.lazy[idx] lowerCAmelCase : List[str] = False if left_element != right_element: lowerCAmelCase : Optional[Any] = self.lazy[idx] lowerCAmelCase : List[Any] = self.lazy[idx] lowerCAmelCase : List[Any] = True lowerCAmelCase : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: lowerCAmelCase : str = val if left_element != right_element: lowerCAmelCase : Optional[Any] = val lowerCAmelCase : Union[str, Any] = val lowerCAmelCase : int = True lowerCAmelCase : int = True return True lowerCAmelCase : List[str] = (left_element + right_element) // 2 self.update(self.left(snake_case__ ) , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) self.update(self.right(snake_case__ ) , mid + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowerCAmelCase : Optional[int] = max( self.segment_tree[self.left(snake_case__ )] , self.segment_tree[self.right(snake_case__ )] ) return True def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" if self.flag[idx] is True: lowerCAmelCase : List[Any] = self.lazy[idx] lowerCAmelCase : str = False if left_element != right_element: lowerCAmelCase : Tuple = self.lazy[idx] lowerCAmelCase : List[Any] = self.lazy[idx] lowerCAmelCase : Optional[int] = True lowerCAmelCase : str = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] lowerCAmelCase : Any = (left_element + right_element) // 2 lowerCAmelCase : Optional[int] = self.query(self.left(snake_case__ ) , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowerCAmelCase : Dict = self.query(self.right(snake_case__ ) , mid + 1 , snake_case__ , snake_case__ , snake_case__ ) return max(snake_case__ , snake_case__ ) def __str__( self ): """simple docstring""" return str([self.query(1 , 1 , self.size , snake_case__ , snake_case__ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase__ = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] lowerCAmelCase__ = 15 lowerCAmelCase__ = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
108
1
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase :int = WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def lowerCamelCase ( lowerCAmelCase : Tuple ): """simple docstring""" __magic_name__ : Optional[Any] = test_results.split(' ' ) __magic_name__ : Tuple = 0 __magic_name__ : List[str] = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __magic_name__ : Optional[int] = expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowerCAmelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def lowerCamelCase ( lowerCAmelCase : Union[str, Any] ): """simple docstring""" __magic_name__ : Optional[int] = {} __magic_name__ : Optional[Any] = None __magic_name__ : Optional[Any] = False for line in failures_short_lines.split('\n' ): if re.search(R'_ \[doctest\]' , lowerCAmelCase ): __magic_name__ : int = True __magic_name__ : Optional[Any] = line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): __magic_name__ : Optional[int] = line __magic_name__ : List[Any] = False return failures class _lowerCamelCase : '''simple docstring''' def __init__( self : Optional[int] , _A : str , _A : Dict ) -> int: __magic_name__ : int = title __magic_name__ : Optional[int] = doc_test_results['time_spent'].split(',' )[0] __magic_name__ : int = doc_test_results['success'] __magic_name__ : List[Any] = doc_test_results['failures'] __magic_name__ : Any = self.n_success + self.n_failures # Failures and success of the modeling tests __magic_name__ : Optional[Any] = doc_test_results @property def __lowerCAmelCase ( self : Dict ) -> str: __magic_name__ : Union[str, Any] = [self._time_spent] __magic_name__ : str = 0 for time in time_spent: __magic_name__ : Any = time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(_A ) == 1: __magic_name__ : Union[str, Any] = [0, 0, time_parts[0]] __magic_name__ , __magic_name__ , __magic_name__ : int = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3600 + minutes * 60 + seconds __magic_name__ , __magic_name__ , __magic_name__ : int = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F'{int(_A )}h{int(_A )}m{int(_A )}s' @property def __lowerCAmelCase ( self : str ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def __lowerCAmelCase ( self : Dict ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": F'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( F'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' F' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def __lowerCAmelCase ( self : str ) -> Dict: __magic_name__ : List[Any] = 40 __magic_name__ : int = {k: v['failed'] for k, v in doc_test_results.items() if isinstance(_A , _A )} __magic_name__ : Optional[Any] = '' for category, failures in category_failures.items(): if len(_A ) == 0: continue if report != "": report += "\n\n" report += F'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(_A ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F'The following examples had failures:\n\n\n{report}\n', }, } @property def __lowerCAmelCase ( self : List[str] ) -> str: __magic_name__ : int = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(_A ) @staticmethod def __lowerCAmelCase ( ) -> int: __magic_name__ : Dict = [ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(_A )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=_A , ) def __lowerCAmelCase ( self : List[str] ) -> Dict: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) __magic_name__ : Any = F'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' __magic_name__ : str = client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=_A , ) def __lowerCAmelCase ( self : Any , _A : List[str] , _A : int , _A : List[str] , _A : str ) -> Any: __magic_name__ : Union[str, Any] = '' for key, value in failures.items(): __magic_name__ : Tuple = value[:200] + ' [Truncated]' if len(_A ) > 250 else value failures_text += F'*{key}*\n_{value}_\n\n' __magic_name__ : List[Any] = job_name __magic_name__ : Any = {'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: __magic_name__ : Optional[Any] = { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def __lowerCAmelCase ( self : Union[str, Any] ) -> str: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) __magic_name__ : Optional[int] = self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) __magic_name__ : Tuple = sorted(self.doc_test_results.items() , key=lambda _A : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): __magic_name__ : Tuple = F'*Num failures* :{len(job_result["failed"] )} \n' __magic_name__ : str = job_result['failures'] __magic_name__ : Optional[Any] = self.get_reply_blocks(_A , _A , _A , text=_A ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=F'Results for {job}' , blocks=_A , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def lowerCamelCase ( ): """simple docstring""" __magic_name__ : Any = os.environ['GITHUB_RUN_ID'] __magic_name__ : str = f'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' __magic_name__ : str = requests.get(lowerCAmelCase ).json() __magic_name__ : Optional[Any] = {} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) __magic_name__ : Optional[int] = math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowerCAmelCase ): __magic_name__ : int = requests.get(url + f'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.' , lowerCAmelCase ) return {} def lowerCamelCase ( lowerCAmelCase : str ): """simple docstring""" __magic_name__ : Dict = {} if os.path.exists(lowerCAmelCase ): __magic_name__ : int = os.listdir(lowerCAmelCase ) for file in files: try: with open(os.path.join(lowerCAmelCase , lowerCAmelCase ) , encoding='utf-8' ) as f: __magic_name__ : Dict = f.read() except UnicodeDecodeError as e: raise ValueError(f'Could not open {os.path.join(lowerCAmelCase , lowerCAmelCase )}.' ) from e return _artifact def lowerCamelCase ( ): """simple docstring""" class _lowerCamelCase : '''simple docstring''' def __init__( self : Any , _A : str ) -> Optional[int]: __magic_name__ : Any = name __magic_name__ : Optional[int] = [] def __str__( self : List[Any] ) -> Dict: return self.name def __lowerCAmelCase ( self : Dict , _A : str ) -> str: self.paths.append({'name': self.name, 'path': path} ) __magic_name__ : Dict[str, Artifact] = {} __magic_name__ : int = filter(os.path.isdir , os.listdir() ) for directory in directories: __magic_name__ : List[str] = directory if artifact_name not in _available_artifacts: __magic_name__ : str = Artifact(lowerCAmelCase ) _available_artifacts[artifact_name].add_path(lowerCAmelCase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase :Optional[int] = get_job_links() lowerCAmelCase :Any = retrieve_available_artifacts() lowerCAmelCase :Union[str, Any] = collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase :int = { v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase :List[str] = github_actions_job_links.get('''run_doctests''') lowerCAmelCase :List[str] = available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] lowerCAmelCase :Optional[int] = retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase :str = handle_test_results(artifact['''stats''']) lowerCAmelCase :Any = failed lowerCAmelCase :Any = success lowerCAmelCase :int = time_spent[1:-1] + ''', ''' lowerCAmelCase :Tuple = extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): lowerCAmelCase :Union[str, Any] = line.replace('''FAILED ''', '''''') lowerCAmelCase :List[Any] = line.split()[0].replace('''\n''', '''''') if "::" in line: lowerCAmelCase , lowerCAmelCase :Dict = line.split('''::''') else: lowerCAmelCase , lowerCAmelCase :Tuple = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase :str = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase :Optional[Any] = all_failures[test] if test in all_failures else '''N/A''' lowerCAmelCase :Dict = failure break lowerCAmelCase :Dict = Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
275
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase :str = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase :List[str] = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase :List[str] = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase :Optional[Any] = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys lowerCAmelCase :Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
275
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging A: str = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : Optional[Any] = ['input_features', 'attention_mask'] def __init__( self , _SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=16000 , _SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> Dict: '''simple docstring''' super().__init__(feature_size=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , padding_value=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Union[str, Any] = num_mel_bins UpperCAmelCase : Tuple = do_ceptral_normalize UpperCAmelCase : Optional[int] = normalize_means UpperCAmelCase : Any = normalize_vars UpperCAmelCase : Any = True def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , ) -> np.ndarray: '''simple docstring''' UpperCAmelCase : Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers UpperCAmelCase : List[Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) UpperCAmelCase : Dict = ta_kaldi.fbank(_SCREAMING_SNAKE_CASE , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: UpperCAmelCase : Tuple = x[:input_length].mean(axis=0 ) UpperCAmelCase : Optional[Any] = np.subtract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if normalize_vars: UpperCAmelCase : Tuple = x[:input_length].std(axis=0 ) UpperCAmelCase : Dict = np.divide(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if input_length < x.shape[0]: UpperCAmelCase : Optional[int] = padding_value # make sure array is in float32 UpperCAmelCase : Any = x.astype(np.floataa ) return x def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[np.ndarray]: '''simple docstring''' UpperCAmelCase : Any = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" F" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" F" {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) UpperCAmelCase : Union[str, Any] = isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"Only mono-channel audio is supported for input to {self}" ) UpperCAmelCase : Union[str, Any] = is_batched_numpy or ( isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCAmelCase : Any = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): UpperCAmelCase : Union[str, Any] = np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): UpperCAmelCase : Tuple = raw_speech.astype(np.floataa ) # always return batch if not is_batched: UpperCAmelCase : List[str] = [raw_speech] # extract fbank features UpperCAmelCase : Optional[int] = [self._extract_fbank_features(_SCREAMING_SNAKE_CASE ) for waveform in raw_speech] # convert into correct format for padding UpperCAmelCase : Optional[Any] = BatchFeature({"""input_features""": features} ) UpperCAmelCase : Tuple = self.pad( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # make sure list is in array format UpperCAmelCase : str = padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , _SCREAMING_SNAKE_CASE ): UpperCAmelCase : Optional[int] = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in input_features] UpperCAmelCase : Optional[Any] = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: UpperCAmelCase : int = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: UpperCAmelCase : List[str] = ( np.array(_SCREAMING_SNAKE_CASE , dtype=np.intaa ) if self._get_padding_strategies(_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) is not PaddingStrategy.DO_NOT_PAD else None ) UpperCAmelCase : Optional[int] = self.normalize( padded_inputs["""input_features"""] , attention_mask=_SCREAMING_SNAKE_CASE ) if return_tensors is not None: UpperCAmelCase : List[str] = padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE ) return padded_inputs
109
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 __lowercase (unittest.TestCase ): _UpperCamelCase = ViTImageProcessor if is_vision_available() else None @property def UpperCamelCase__ ( self ) ->str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Tuple = (3, 32, 128) __lowerCAmelCase : List[str] = tempfile.mkdtemp() # fmt: off __lowerCAmelCase : List[str] = ['''[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 __lowerCAmelCase : Optional[int] = dict(zip(A_ , range(len(A_ ) ) ) ) __lowerCAmelCase : Tuple = 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''' ) __lowerCAmelCase : Union[str, Any] = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } __lowerCAmelCase : 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 UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __lowerCAmelCase : str = Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) return image_input def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : Dict = self.get_tokenizer() __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : 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 UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : Union[str, Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : List[Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCAmelCase : int = self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __lowerCAmelCase : int = 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 UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Any = self.get_image_processor() __lowerCAmelCase : Optional[Any] = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Optional[int] = self.prepare_image_inputs() __lowerCAmelCase : Optional[Any] = image_processor(A_ , return_tensors='''np''' ) __lowerCAmelCase : Tuple = 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 UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Union[str, Any] = self.get_tokenizer() __lowerCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Any = '''test''' __lowerCAmelCase : Dict = processor(text=A_ ) __lowerCAmelCase : str = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Dict = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : str = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = '''test''' __lowerCAmelCase : int = self.prepare_image_inputs() __lowerCAmelCase : int = 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 UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : int = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase : Optional[int] = processor.char_decode(A_ ) __lowerCAmelCase : Tuple = tokenizer.batch_decode(A_ ) __lowerCAmelCase : Any = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(A_ , A_ ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[Any] = self.prepare_image_inputs() __lowerCAmelCase : List[Any] = processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[str] = self.get_image_processor() __lowerCAmelCase : List[str] = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = torch.randn(1 , 27 , 38 ) __lowerCAmelCase : Optional[int] = torch.randn(1 , 27 , 5_0257 ) __lowerCAmelCase : Optional[Any] = torch.randn(1 , 27 , 3_0522 ) __lowerCAmelCase : List[str] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
275
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __lowercase = logging.get_logger(__name__) __lowercase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' for attribute in key.split('''.''' ): __UpperCamelCase :List[Any] = getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if weight_type is not None: __UpperCamelCase :Dict = getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).shape else: __UpperCamelCase :int = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": __UpperCamelCase :Dict = value elif weight_type == "weight_g": __UpperCamelCase :Optional[Any] = value elif weight_type == "weight_v": __UpperCamelCase :str = value elif weight_type == "bias": __UpperCamelCase :List[Any] = value else: __UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Dict = [] __UpperCamelCase :Dict = fairseq_model.state_dict() __UpperCamelCase :Optional[Any] = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase :List[Any] = False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == '''group''' , ) __UpperCamelCase :List[Any] = True else: for key, mapped_key in MAPPING.items(): __UpperCamelCase :Tuple = '''hubert.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or (key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0] and not is_finetuned): __UpperCamelCase :Tuple = True if "*" in mapped_key: __UpperCamelCase :str = name.split(SCREAMING_SNAKE_CASE )[0].split('''.''' )[-2] __UpperCamelCase :Union[str, Any] = mapped_key.replace('''*''' , SCREAMING_SNAKE_CASE ) if "weight_g" in name: __UpperCamelCase :List[Any] = '''weight_g''' elif "weight_v" in name: __UpperCamelCase :Any = '''weight_v''' elif "weight" in name: __UpperCamelCase :Optional[int] = '''weight''' elif "bias" in name: __UpperCamelCase :Union[str, Any] = '''bias''' else: __UpperCamelCase :List[Any] = None set_recursively(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :int = full_name.split('''conv_layers.''' )[-1] __UpperCamelCase :Union[str, Any] = name.split('''.''' ) __UpperCamelCase :Tuple = int(items[0] ) __UpperCamelCase :Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __UpperCamelCase :Optional[int] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __UpperCamelCase :Any = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __UpperCamelCase :int = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True ): '''simple docstring''' if config_path is not None: __UpperCamelCase :List[Any] = HubertConfig.from_pretrained(SCREAMING_SNAKE_CASE ) else: __UpperCamelCase :str = HubertConfig() if is_finetuned: if dict_path: __UpperCamelCase :str = Dictionary.load(SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase :List[str] = target_dict.pad_index __UpperCamelCase :int = target_dict.bos_index __UpperCamelCase :List[str] = target_dict.eos_index __UpperCamelCase :Any = len(target_dict.symbols ) __UpperCamelCase :str = os.path.join(SCREAMING_SNAKE_CASE , '''vocab.json''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(SCREAMING_SNAKE_CASE ) ) return os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices , SCREAMING_SNAKE_CASE ) __UpperCamelCase :List[Any] = WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=SCREAMING_SNAKE_CASE , ) __UpperCamelCase :Optional[int] = True if config.feat_extract_norm == '''layer''' else False __UpperCamelCase :Union[str, Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , ) __UpperCamelCase :Optional[Any] = WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Tuple = HubertForCTC(SCREAMING_SNAKE_CASE ) else: __UpperCamelCase :Optional[Any] = HubertModel(SCREAMING_SNAKE_CASE ) if is_finetuned: __UpperCamelCase :Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __UpperCamelCase :str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __UpperCamelCase :int = model[0].eval() recursively_load_weights(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __lowercase = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
354
def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if not grid or not grid[0]: raise TypeError('''The grid does not contain the appropriate information''' ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] __UpperCamelCase :Union[str, Any] = grid[0] for row_n in range(1 , len(SCREAMING_SNAKE_CASE ) ): __UpperCamelCase :Optional[int] = grid[row_n] __UpperCamelCase :Dict = fill_row(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __UpperCamelCase :Any = grid[row_n] return grid[-1][-1] def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' current_row[0] += row_above[0] for cell_n in range(1 , len(SCREAMING_SNAKE_CASE ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
105
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' _a = DDIMPipeline _a = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _a = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } _a = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS _a = False def snake_case ( self : str )-> Optional[Any]: torch.manual_seed(0 ) lowerCamelCase__ : Union[str, Any] =UNetaDModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=3, out_channels=3, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D'''), up_block_types=('''AttnUpBlock2D''', '''UpBlock2D'''), ) lowerCamelCase__ : Optional[Any] =DDIMScheduler() lowerCamelCase__ : List[Any] ={'''unet''': unet, '''scheduler''': scheduler} return components def snake_case ( self : Optional[Any], lowerCamelCase : Dict, lowerCamelCase : Optional[Any]=0 )-> Optional[int]: if str(lowerCamelCase ).startswith('''mps''' ): lowerCamelCase__ : Dict =torch.manual_seed(lowerCamelCase ) else: lowerCamelCase__ : Optional[int] =torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) lowerCamelCase__ : Tuple ={ '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def snake_case ( self : Dict )-> str: lowerCamelCase__ : Optional[Any] ='''cpu''' lowerCamelCase__ : int =self.get_dummy_components() lowerCamelCase__ : Optional[int] =self.pipeline_class(**lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) lowerCamelCase__ : List[str] =self.get_dummy_inputs(lowerCamelCase ) lowerCamelCase__ : Any =pipe(**lowerCamelCase ).images lowerCamelCase__ : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 32, 32, 3) ) lowerCamelCase__ : Tuple =np.array( [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] ) lowerCamelCase__ : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase, 1E-3 ) def snake_case ( self : Union[str, Any] )-> List[Any]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def snake_case ( self : Union[str, Any] )-> int: super().test_save_load_local(expected_max_difference=3E-3 ) def snake_case ( self : List[Any] )-> List[Any]: super().test_save_load_optional_components(expected_max_difference=3E-3 ) def snake_case ( self : Optional[Any] )-> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def snake_case ( self : Optional[Any] )-> List[str]: lowerCamelCase__ : Optional[Any] ='''google/ddpm-cifar10-32''' lowerCamelCase__ : Union[str, Any] =UNetaDModel.from_pretrained(lowerCamelCase ) lowerCamelCase__ : Optional[int] =DDIMScheduler() lowerCamelCase__ : int =DDIMPipeline(unet=lowerCamelCase, scheduler=lowerCamelCase ) ddim.to(lowerCamelCase ) ddim.set_progress_bar_config(disable=lowerCamelCase ) lowerCamelCase__ : Tuple =torch.manual_seed(0 ) lowerCamelCase__ : int =ddim(generator=lowerCamelCase, eta=0.0, output_type='''numpy''' ).images lowerCamelCase__ : Tuple =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase__ : Any =np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case ( self : Optional[int] )-> Any: lowerCamelCase__ : str ='''google/ddpm-ema-bedroom-256''' lowerCamelCase__ : Optional[int] =UNetaDModel.from_pretrained(lowerCamelCase ) lowerCamelCase__ : Any =DDIMScheduler.from_pretrained(lowerCamelCase ) lowerCamelCase__ : Optional[Any] =DDIMPipeline(unet=lowerCamelCase, scheduler=lowerCamelCase ) ddpm.to(lowerCamelCase ) ddpm.set_progress_bar_config(disable=lowerCamelCase ) lowerCamelCase__ : List[str] =torch.manual_seed(0 ) lowerCamelCase__ : Optional[Any] =ddpm(generator=lowerCamelCase, output_type='''numpy''' ).images lowerCamelCase__ : Any =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowerCamelCase__ : Any =np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
238
"""simple docstring""" import argparse import os import re _lowercase : str = "src/diffusers" # Pattern that looks at the indentation in a line. _lowercase : List[Any] = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowercase : int = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowercase : Optional[int] = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowercase : List[Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowercase : str = re.compile(r"\[([^\]]+)\]") def snake_case__ ( __lowerCamelCase : Optional[int] ): """simple docstring""" lowerCamelCase__ : List[str] =_re_indent.search(__lowerCamelCase ) return "" if search is None else search.groups()[0] def snake_case__ ( __lowerCamelCase : Any , __lowerCamelCase : List[Any]="" , __lowerCamelCase : int=None , __lowerCamelCase : Optional[int]=None ): """simple docstring""" lowerCamelCase__ : Optional[int] =0 lowerCamelCase__ : Any =code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__lowerCamelCase ): index += 1 lowerCamelCase__ : Dict =['''\n'''.join(lines[:index] )] else: lowerCamelCase__ : Tuple =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase__ : int =[lines[index]] index += 1 while index < len(__lowerCamelCase ) and (end_prompt is None or not lines[index].startswith(__lowerCamelCase )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__lowerCamelCase ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__lowerCamelCase ) ) if index < len(__lowerCamelCase ) - 1: lowerCamelCase__ : str =[lines[index + 1]] index += 1 else: lowerCamelCase__ : str =[] else: blocks.append('''\n'''.join(__lowerCamelCase ) ) lowerCamelCase__ : str =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__lowerCamelCase ) > 0: blocks.append('''\n'''.join(__lowerCamelCase ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__lowerCamelCase ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def snake_case__ ( __lowerCamelCase : Any ): """simple docstring""" def _inner(__lowerCamelCase : Any ): return key(__lowerCamelCase ).lower().replace('''_''' , '''''' ) return _inner def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : Any=None ): """simple docstring""" # If no key is provided, we use a noop. def noop(__lowerCamelCase : List[str] ): return x if key is None: lowerCamelCase__ : Tuple =noop # Constants are all uppercase, they go first. lowerCamelCase__ : Union[str, Any] =[obj for obj in objects if key(__lowerCamelCase ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase__ : Optional[int] =[obj for obj in objects if key(__lowerCamelCase )[0].isupper() and not key(__lowerCamelCase ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase__ : Optional[Any] =[obj for obj in objects if not key(__lowerCamelCase )[0].isupper()] lowerCamelCase__ : int =ignore_underscore(__lowerCamelCase ) return sorted(__lowerCamelCase , key=__lowerCamelCase ) + sorted(__lowerCamelCase , key=__lowerCamelCase ) + sorted(__lowerCamelCase , key=__lowerCamelCase ) def snake_case__ ( __lowerCamelCase : Optional[Any] ): """simple docstring""" # This inner function sort imports between [ ]. def _replace(__lowerCamelCase : Optional[Any] ): lowerCamelCase__ : Dict =match.groups()[0] if "," not in imports: return f'''[{imports}]''' lowerCamelCase__ : List[Any] =[part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase__ : Optional[int] =keys[:-1] return "[" + ", ".join([f'''"{k}"''' for k in sort_objects(__lowerCamelCase )] ) + "]" lowerCamelCase__ : List[Any] =import_statement.split('''\n''' ) if len(__lowerCamelCase ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase__ : Tuple =2 if lines[1].strip() == '''[''' else 1 lowerCamelCase__ : Any =[(i, _re_strip_line.search(__lowerCamelCase ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase__ : List[Any] =sort_objects(__lowerCamelCase , key=lambda __lowerCamelCase : x[1] ) lowerCamelCase__ : Union[str, Any] =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__lowerCamelCase ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase__ : List[str] =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase__ : str =[part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase__ : Any =keys[:-1] lowerCamelCase__ : List[Any] =get_indent(lines[1] ) + ''', '''.join([f'''"{k}"''' for k in sort_objects(__lowerCamelCase )] ) return "\n".join(__lowerCamelCase ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase__ : Union[str, Any] =_re_bracket_content.sub(_replace , __lowerCamelCase ) return import_statement def snake_case__ ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any]=True ): """simple docstring""" with open(__lowerCamelCase , '''r''' ) as f: lowerCamelCase__ : Optional[int] =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase__ : int =split_code_in_indented_blocks( __lowerCamelCase , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__lowerCamelCase ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase__ : Optional[Any] =main_blocks[block_idx] lowerCamelCase__ : List[str] =block.split('''\n''' ) # Get to the start of the imports. lowerCamelCase__ : Any =0 while line_idx < len(__lowerCamelCase ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase__ : Tuple =len(__lowerCamelCase ) else: line_idx += 1 if line_idx >= len(__lowerCamelCase ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase__ : Any ='''\n'''.join(block_lines[line_idx:-1] ) lowerCamelCase__ : Dict =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase__ : List[Any] =split_code_in_indented_blocks(__lowerCamelCase , indent_level=__lowerCamelCase ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase__ : List[Any] =_re_direct_key if '''_import_structure''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase__ : Union[str, Any] =[(pattern.search(__lowerCamelCase ).groups()[0] if pattern.search(__lowerCamelCase ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase__ : Optional[Any] =[(i, key) for i, key in enumerate(__lowerCamelCase ) if key is not None] lowerCamelCase__ : List[Any] =[x[0] for x in sorted(__lowerCamelCase , key=lambda __lowerCamelCase : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase__ : Optional[Any] =0 lowerCamelCase__ : Tuple =[] for i in range(len(__lowerCamelCase ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase__ : List[Any] =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(__lowerCamelCase ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase__ : str ='''\n'''.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(__lowerCamelCase ): if check_only: return True else: print(f'''Overwriting {file}.''' ) with open(__lowerCamelCase , '''w''' ) as f: f.write('''\n'''.join(__lowerCamelCase ) ) def snake_case__ ( __lowerCamelCase : Optional[Any]=True ): """simple docstring""" lowerCamelCase__ : Any =[] for root, _, files in os.walk(__lowerCamelCase ): if "__init__.py" in files: lowerCamelCase__ : Tuple =sort_imports(os.path.join(__lowerCamelCase , '''__init__.py''' ) , check_only=__lowerCamelCase ) if result: lowerCamelCase__ : List[str] =[os.path.join(__lowerCamelCase , '''__init__.py''' )] if len(__lowerCamelCase ) > 0: raise ValueError(f'''Would overwrite {len(__lowerCamelCase )} files, run `make style`.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowercase : List[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
238
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Tuple = logging.get_logger(__name__) lowercase : int = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class A ( __snake_case ): __magic_name__ = '''vit_msn''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-06 , SCREAMING_SNAKE_CASE=224 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> int: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : List[Any] = num_hidden_layers A : Dict = num_attention_heads A : str = intermediate_size A : str = hidden_act A : Union[str, Any] = hidden_dropout_prob A : str = attention_probs_dropout_prob A : List[str] = initializer_range A : Dict = layer_norm_eps A : Any = image_size A : Optional[int] = patch_size A : Optional[int] = num_channels A : Union[str, Any] = qkv_bias
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
from typing import List import numpy as np def UpperCAmelCase_ ( __lowerCAmelCase ) -> int: __lowercase : Optional[Any] = {key: len(__lowerCAmelCase ) for key, value in gen_kwargs.items() if isinstance(__lowerCAmelCase , __lowerCAmelCase )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( '''Sharding is ambiguous for this dataset: ''' + '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n''' + '''\n'''.join(F'\t- key {key} has length {length}' for key, length in lists_lengths.items() ) + '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ''' + '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.''' ) ) __lowercase : Union[str, Any] = max(lists_lengths.values() , default=0 ) return max(1 , __lowerCAmelCase ) def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> List[range]: __lowercase : Dict = [] for group_idx in range(__lowerCAmelCase ): __lowercase : Optional[Any] = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __lowercase : Any = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __lowercase : Dict = range(__lowerCAmelCase , start + num_shards_to_add ) shards_indices_per_group.append(__lowerCAmelCase ) return shards_indices_per_group def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> List[dict]: __lowercase : Optional[Any] = _number_of_shards_in_gen_kwargs(__lowerCAmelCase ) if num_shards == 1: return [dict(__lowerCAmelCase )] else: __lowercase : List[Any] = _distribute_shards(num_shards=__lowerCAmelCase , max_num_jobs=__lowerCAmelCase ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(__lowerCAmelCase ) ) ] def UpperCAmelCase_ ( __lowerCAmelCase ) -> dict: return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , __lowerCAmelCase ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> dict: __lowercase : Dict = {len(__lowerCAmelCase ) for value in gen_kwargs.values() if isinstance(__lowerCAmelCase , __lowerCAmelCase )} __lowercase : str = {} for size in list_sizes: __lowercase : Optional[Any] = list(range(__lowerCAmelCase ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __lowercase : Union[str, Any] = dict(__lowerCAmelCase ) for key, value in shuffled_kwargs.items(): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowercase : List[str] = [value[i] for i in indices_per_size[len(__lowerCAmelCase )]] return shuffled_kwargs
156
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : Optional[torch.FloatTensor] = None A__ : torch.FloatTensor = None A__ : Optional[Tuple[torch.FloatTensor]] = None A__ : Optional[Tuple[torch.FloatTensor]] = None class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , _snake_case : int=1 , _snake_case : int=0 , _snake_case : List[str]=2 , _snake_case : List[str]=512 , _snake_case : Tuple="cls" , _snake_case : Union[str, Any]=False , _snake_case : str=True , **_snake_case : Union[str, Any] , ): super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) __lowercase : Union[str, Any] = project_dim __lowercase : str = pooler_fn __lowercase : List[str] = learn_encoder __lowercase : int = use_attention_mask class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : Any = [r'''pooler''', r'''logit_scale'''] A__ : Dict = [r'''position_ids''', r'''predictions.decoder.bias'''] A__ : Union[str, Any] = '''roberta''' A__ : str = RobertaSeriesConfig def __init__( self : List[str] , _snake_case : Any ): super().__init__(_snake_case ) __lowercase : Union[str, Any] = XLMRobertaModel(_snake_case ) __lowercase : Optional[int] = nn.Linear(config.hidden_size , config.project_dim ) __lowercase : Optional[int] = getattr(_snake_case , '''has_pre_transformation''' , _snake_case ) if self.has_pre_transformation: __lowercase : Union[str, Any] = nn.Linear(config.hidden_size , config.project_dim ) __lowercase : Any = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def snake_case_ ( self : Dict , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[bool] = None , _snake_case : Optional[bool] = None , _snake_case : Optional[bool] = None , ): __lowercase : List[str] = return_dict if return_dict is not None else self.config.use_return_dict __lowercase : Any = self.base_model( input_ids=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , position_ids=_snake_case , head_mask=_snake_case , inputs_embeds=_snake_case , encoder_hidden_states=_snake_case , encoder_attention_mask=_snake_case , output_attentions=_snake_case , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=_snake_case , ) if self.has_pre_transformation: __lowercase : Optional[int] = outputs['''hidden_states'''][-2] __lowercase : Union[str, Any] = self.pre_LN(_snake_case ) __lowercase : Optional[int] = self.transformation_pre(_snake_case ) return TransformationModelOutput( projection_state=_snake_case , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __lowercase : str = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=_snake_case , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
156
1
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black __A = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. __A = ' \"""\n Output class for the scheduler\'s step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"""\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n' class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self ) -> int: _lowerCAmelCase =tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , """schedulers/""" ) ) _lowerCAmelCase =self.diffusers_dir shutil.copy( os.path.join(__UpperCAmelCase , """src/diffusers/schedulers/scheduling_ddpm.py""" ) , os.path.join(self.diffusers_dir , """schedulers/scheduling_ddpm.py""" ) , ) def _lowerCAmelCase ( self ) -> Dict: _lowerCAmelCase ="""src/diffusers""" shutil.rmtree(self.diffusers_dir ) def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ) -> Tuple: _lowerCAmelCase =comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: _lowerCAmelCase =comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result _lowerCAmelCase =black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) _lowerCAmelCase =black.format_str(__UpperCAmelCase , mode=__UpperCAmelCase ) _lowerCAmelCase =os.path.join(self.diffusers_dir , """new_code.py""" ) with open(__UpperCAmelCase , """w""" , newline="""\n""" ) as f: f.write(__UpperCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__UpperCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__UpperCAmelCase ) with open(__UpperCAmelCase , """r""" ) as f: self.assertTrue(f.read() , __UpperCAmelCase ) def _lowerCAmelCase ( self ) -> Optional[int]: _lowerCAmelCase =check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def _lowerCAmelCase ( self ) -> str: # Base copy consistency self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , __UpperCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , re.sub("""DDPM""" , """Test""" , __UpperCAmelCase ) , ) # Copy consistency with a really long name _lowerCAmelCase ="""TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' , f'''{long_class_name}SchedulerOutput''' , re.sub("""Bert""" , __UpperCAmelCase , __UpperCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , __UpperCAmelCase , overwrite_result=re.sub("""DDPM""" , """Test""" , __UpperCAmelCase ) , )
341
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowerCamelCase__ : '''simple docstring''' lowerCamelCase = XGLMConfig lowerCamelCase = {} lowerCamelCase = '''gelu''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase=14 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=2 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_12 , __UpperCAmelCase=0.0_2 , ) -> List[str]: _lowerCAmelCase =parent _lowerCAmelCase =batch_size _lowerCAmelCase =seq_length _lowerCAmelCase =is_training _lowerCAmelCase =use_input_mask _lowerCAmelCase =use_labels _lowerCAmelCase =vocab_size _lowerCAmelCase =d_model _lowerCAmelCase =num_hidden_layers _lowerCAmelCase =num_attention_heads _lowerCAmelCase =ffn_dim _lowerCAmelCase =activation_function _lowerCAmelCase =activation_dropout _lowerCAmelCase =attention_dropout _lowerCAmelCase =max_position_embeddings _lowerCAmelCase =initializer_range _lowerCAmelCase =None _lowerCAmelCase =0 _lowerCAmelCase =2 _lowerCAmelCase =1 def _lowerCAmelCase ( self ) -> Dict: return XGLMConfig.from_pretrained("""facebook/xglm-564M""" ) def _lowerCAmelCase ( self ) -> str: _lowerCAmelCase =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) _lowerCAmelCase =None if self.use_input_mask: _lowerCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase =self.get_config() _lowerCAmelCase =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def _lowerCAmelCase ( self ) -> str: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=__UpperCAmelCase , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=__UpperCAmelCase , ) def _lowerCAmelCase ( self ) -> Dict: _lowerCAmelCase =self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) =config_and_inputs _lowerCAmelCase ={ """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowerCamelCase__ ( __magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () lowerCamelCase = (TFXGLMForCausalLM,) if is_tf_available() else () lowerCamelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def _lowerCAmelCase ( self ) -> Tuple: _lowerCAmelCase =TFXGLMModelTester(self ) _lowerCAmelCase =ConfigTester(self , config_class=__UpperCAmelCase , n_embd=37 ) def _lowerCAmelCase ( self ) -> int: self.config_tester.run_common_tests() @slow def _lowerCAmelCase ( self ) -> Union[str, Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase =TFXGLMModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""" ) def _lowerCAmelCase ( self ) -> Union[str, Any]: super().test_resize_token_embeddings() @require_tf class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def _lowerCAmelCase ( self , __UpperCAmelCase=True ) -> str: _lowerCAmelCase =TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""" ) _lowerCAmelCase =tf.convert_to_tensor([[2, 2_68, 98_65]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCAmelCase =[2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81] # fmt: on _lowerCAmelCase =model.generate(__UpperCAmelCase , do_sample=__UpperCAmelCase , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , __UpperCAmelCase ) @slow def _lowerCAmelCase ( self ) -> Optional[Any]: _lowerCAmelCase =XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) _lowerCAmelCase =TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""" ) tf.random.set_seed(0 ) _lowerCAmelCase =tokenizer("""Today is a nice day and""" , return_tensors="""tf""" ) _lowerCAmelCase =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0""" ): _lowerCAmelCase =model.generate(__UpperCAmelCase , do_sample=__UpperCAmelCase , seed=[7, 0] ) _lowerCAmelCase =tokenizer.decode(output_ids[0] , skip_special_tokens=__UpperCAmelCase ) _lowerCAmelCase =( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def _lowerCAmelCase ( self ) -> Union[str, Any]: _lowerCAmelCase =TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""" ) _lowerCAmelCase =XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) _lowerCAmelCase ="""left""" # use different length sentences to test batching _lowerCAmelCase =[ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCAmelCase =tokenizer(__UpperCAmelCase , return_tensors="""tf""" , padding=__UpperCAmelCase ) _lowerCAmelCase =inputs["""input_ids"""] _lowerCAmelCase =model.generate(input_ids=__UpperCAmelCase , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12 ) _lowerCAmelCase =tokenizer(sentences[0] , return_tensors="""tf""" ).input_ids _lowerCAmelCase =model.generate(input_ids=__UpperCAmelCase , max_new_tokens=12 ) _lowerCAmelCase =tokenizer(sentences[1] , return_tensors="""tf""" ).input_ids _lowerCAmelCase =model.generate(input_ids=__UpperCAmelCase , max_new_tokens=12 ) _lowerCAmelCase =tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) _lowerCAmelCase =tokenizer.decode(output_non_padded[0] , skip_special_tokens=__UpperCAmelCase ) _lowerCAmelCase =tokenizer.decode(output_padded[0] , skip_special_tokens=__UpperCAmelCase ) _lowerCAmelCase =[ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , [non_padded_sentence, padded_sentence] )
341
1
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowercase : _a = PegasusConfig _a = {} _a = "gelu" def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=40 , _a=2 , _a=1 , _a=0 , ) -> List[str]: _A : List[Any] = parent _A : Optional[Any] = batch_size _A : Tuple = seq_length _A : int = is_training _A : List[Any] = use_labels _A : int = vocab_size _A : Dict = hidden_size _A : Dict = num_hidden_layers _A : int = num_attention_heads _A : int = intermediate_size _A : Dict = hidden_dropout_prob _A : Dict = attention_probs_dropout_prob _A : Union[str, Any] = max_position_embeddings _A : int = eos_token_id _A : Dict = pad_token_id _A : List[str] = bos_token_id def a__ ( self ) -> str: _A : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A : Any = tf.concat([input_ids, eos_tensor] , axis=1 ) _A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A : Optional[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 , ) _A : List[Any] = prepare_pegasus_inputs_dict(_a , _a , _a ) return config, inputs_dict def a__ ( self , _a , _a ) -> Optional[Any]: _A : Any = TFPegasusModel(config=_a ).get_decoder() _A : Union[str, Any] = inputs_dict["""input_ids"""] _A : Union[str, Any] = input_ids[:1, :] _A : List[str] = inputs_dict["""attention_mask"""][:1, :] _A : Any = inputs_dict["""head_mask"""] _A : Any = 1 # first forward pass _A : int = model(_a , attention_mask=_a , head_mask=_a , use_cache=_a ) _A , _A : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _A : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _A : Dict = tf.concat([input_ids, next_tokens] , axis=-1 ) _A : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _A : Any = model(_a , attention_mask=_a )[0] _A : List[Any] = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _A : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _A : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] _A : int = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_=None,snake_case_=None,snake_case_=None,snake_case_=None,snake_case_=None,): if attention_mask is None: _A : List[str] = tf.cast(tf.math.not_equal(snake_case_,config.pad_token_id ),tf.inta ) if decoder_attention_mask is None: _A : int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],config.pad_token_id ),tf.inta ), ],axis=-1,) if head_mask is None: _A : List[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A : Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () _a = (TFPegasusForConditionalGeneration,) if is_tf_available() else () _a = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) _a = True _a = False _a = False def a__ ( self ) -> Optional[Any]: _A : Tuple = TFPegasusModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a ) def a__ ( self ) -> Optional[int]: self.config_tester.run_common_tests() def a__ ( self ) -> Any: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) @require_sentencepiece @require_tokenizers @require_tf class lowercase ( unittest.TestCase ): _a = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] _a = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers _a = "google/pegasus-xsum" @cached_property def a__ ( self ) -> List[Any]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def a__ ( self ) -> List[Any]: _A : str = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def a__ ( self , **_a ) -> Tuple: _A : Dict = self.translate_src_text(**_a ) assert self.expected_text == generated_words def a__ ( self , **_a ) -> Any: _A : str = self.tokenizer(self.src_text , **_a , padding=_a , return_tensors="""tf""" ) _A : Tuple = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_a , ) _A : List[str] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_a ) return generated_words @slow def a__ ( self ) -> Optional[int]: self._assert_generated_batch_equal_expected()
26
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowerCamelCase : List[str] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( lowercase : Tuple , lowercase : Optional[int] , lowercase : Optional[int] ): '''simple docstring''' return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def _SCREAMING_SNAKE_CASE ( lowercase : np.ndarray , lowercase : Optional[str] , lowercase : Optional[str] ): '''simple docstring''' lowerCamelCase_ = to_pil_image(lowercase ) lowerCamelCase_ , lowerCamelCase_ = pil_image.size lowerCamelCase_ = pytesseract.image_to_data(lowercase , lang=lowercase , output_type='dict' , config=lowercase ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates lowerCamelCase_ = [idx for idx, word in enumerate(lowercase ) if not word.strip()] lowerCamelCase_ = [word for idx, word in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format lowerCamelCase_ = [] for x, y, w, h in zip(lowercase , lowercase , lowercase , lowercase ): lowerCamelCase_ = [x, y, x + w, y + h] actual_boxes.append(lowercase ) # finally, normalize the bounding boxes lowerCamelCase_ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase , lowercase , lowercase ) ) assert len(lowercase ) == len(lowercase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = ['''pixel_values'''] def __init__( self : int , A_ : bool = True , A_ : Dict[str, int] = None , A_ : PILImageResampling = PILImageResampling.BILINEAR , A_ : bool = True , A_ : float = 1 / 255 , A_ : bool = True , A_ : Union[float, Iterable[float]] = None , A_ : Union[float, Iterable[float]] = None , A_ : bool = True , A_ : Optional[str] = None , A_ : Optional[str] = "" , **A_ : Optional[int] , ) -> None: """simple docstring""" super().__init__(**A_ ) lowerCamelCase_ = size if size is not None else {'height': 224, 'width': 224} lowerCamelCase_ = get_size_dict(A_ ) lowerCamelCase_ = do_resize lowerCamelCase_ = size lowerCamelCase_ = resample lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_value lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD lowerCamelCase_ = apply_ocr lowerCamelCase_ = ocr_lang lowerCamelCase_ = tesseract_config def a__ ( self : str , A_ : np.ndarray , A_ : Dict[str, int] , A_ : PILImageResampling = PILImageResampling.BILINEAR , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : str , ) -> np.ndarray: """simple docstring""" lowerCamelCase_ = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) lowerCamelCase_ = (size['height'], size['width']) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def a__ ( self : Any , A_ : np.ndarray , A_ : Union[int, float] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Optional[Any] , ) -> np.ndarray: """simple docstring""" return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def a__ ( self : Union[str, Any] , A_ : np.ndarray , A_ : Union[float, Iterable[float]] , A_ : Union[float, Iterable[float]] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : int , ) -> np.ndarray: """simple docstring""" return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def a__ ( self : List[Any] , A_ : ImageInput , A_ : bool = None , A_ : Dict[str, int] = None , A_ : Dict=None , A_ : bool = None , A_ : float = None , A_ : bool = None , A_ : Union[float, Iterable[float]] = None , A_ : Union[float, Iterable[float]] = None , A_ : bool = None , A_ : Optional[str] = None , A_ : Optional[str] = None , A_ : Optional[Union[str, TensorType]] = None , A_ : ChannelDimension = ChannelDimension.FIRST , **A_ : Any , ) -> PIL.Image.Image: """simple docstring""" lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = size if size is not None else self.size lowerCamelCase_ = get_size_dict(A_ ) lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ = image_std if image_std is not None else self.image_std lowerCamelCase_ = apply_ocr if apply_ocr is not None else self.apply_ocr lowerCamelCase_ = ocr_lang if ocr_lang is not None else self.ocr_lang lowerCamelCase_ = tesseract_config if tesseract_config is not None else self.tesseract_config lowerCamelCase_ = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('If do_normalize is True, image_mean and image_std must be specified.' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(A_ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , 'pytesseract' ) lowerCamelCase_ = [] lowerCamelCase_ = [] for image in images: lowerCamelCase_ , lowerCamelCase_ = apply_tesseract(A_ , A_ , A_ ) words_batch.append(A_ ) boxes_batch.append(A_ ) if do_resize: lowerCamelCase_ = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(A_ , A_ ) for image in images] lowerCamelCase_ = BatchFeature(data={'pixel_values': images} , tensor_type=A_ ) if apply_ocr: lowerCamelCase_ = words_batch lowerCamelCase_ = boxes_batch return data
204
0
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast SCREAMING_SNAKE_CASE : List[str] = datasets.utils.logging.get_logger(__name__) @dataclass class UpperCamelCase ( datasets.BuilderConfig ): '''simple docstring''' lowercase : int =10000 lowercase : Optional[List[str]] =None lowercase : Optional[datasets.Features] =None class UpperCamelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' lowercase : Any =ParquetConfig def UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase ( self , UpperCamelCase_ ): if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}" ) lowercase_ :Any = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCamelCase_ , (str, list, tuple) ): lowercase_ :int = data_files if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowercase_ :Any = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowercase_ :int = [dl_manager.iter_files(UpperCamelCase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] lowercase_ :Optional[int] = [] for split_name, files in data_files.items(): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowercase_ :Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowercase_ :List[str] = [dl_manager.iter_files(UpperCamelCase_ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(UpperCamelCase_ ): with open(UpperCamelCase_ , '''rb''' ) as f: lowercase_ :Any = datasets.Features.from_arrow_schema(pq.read_schema(UpperCamelCase_ ) ) break splits.append(datasets.SplitGenerator(name=UpperCamelCase_ , gen_kwargs={'''files''': files} ) ) return splits def UpperCamelCase ( self , UpperCamelCase_ ): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowercase_ :List[Any] = table_cast(UpperCamelCase_ , self.info.features.arrow_schema ) return pa_table def UpperCamelCase ( self , UpperCamelCase_ ): lowercase_ :Dict = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( f"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCamelCase_ ) ): with open(UpperCamelCase_ , '''rb''' ) as f: lowercase_ :Optional[int] = pq.ParquetFile(UpperCamelCase_ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): lowercase_ :str = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(UpperCamelCase_ ) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(UpperCamelCase_ )}: {e}" ) raise
365
from __future__ import annotations from random import random class UpperCamelCase : '''simple docstring''' def __init__( self , UpperCamelCase_ = None ): lowercase_ :Tuple = value lowercase_ :Tuple = random() lowercase_ :Node | None = None lowercase_ :Node | None = None def __repr__( self ): from pprint import pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)} , indent=1 ) def __str__( self ): lowercase_ :Optional[int] = str(self.value ) + ''' ''' lowercase_ :List[str] = str(self.left or '''''' ) lowercase_ :List[Any] = str(self.right or '''''' ) return value + left + right def UpperCamelCase ( _a , _a ) -> tuple[Node | None, Node | None]: '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: lowercase_ , lowercase_ :List[Any] = split(root.left , _a ) return left, root else: lowercase_ , lowercase_ :Tuple = split(root.right , _a ) return root, right def UpperCamelCase ( _a , _a ) -> Node | None: '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: lowercase_ :Tuple = merge(left.right , _a ) return left else: lowercase_ :Optional[int] = merge(_a , right.left ) return right def UpperCamelCase ( _a , _a ) -> Node | None: '''simple docstring''' lowercase_ :str = Node(_a ) lowercase_ , lowercase_ :Dict = split(_a , _a ) return merge(merge(_a , _a ) , _a ) def UpperCamelCase ( _a , _a ) -> Node | None: '''simple docstring''' lowercase_ , lowercase_ :List[str] = split(_a , value - 1 ) lowercase_ , lowercase_ :Tuple = split(_a , _a ) return merge(_a , _a ) def UpperCamelCase ( _a ) -> None: '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def UpperCamelCase ( _a , _a ) -> Node | None: '''simple docstring''' for arg in args.split(): if arg[0] == "+": lowercase_ :Any = insert(_a , int(arg[1:] ) ) elif arg[0] == "-": lowercase_ :Optional[int] = erase(_a , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def UpperCamelCase ( ) -> None: '''simple docstring''' lowercase_ :List[Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) lowercase_ :Optional[Any] = input() while args != "q": lowercase_ :Union[str, Any] = interact_treap(_a , _a ) print(_a ) lowercase_ :str = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
252
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class _UpperCAmelCase : def __init__( self : List[str] , A : Any , ) -> Dict: lowercase_ : Tuple = parent lowercase_ : str = 13 lowercase_ : Optional[Any] = 7 lowercase_ : Any = True lowercase_ : str = True lowercase_ : List[str] = True lowercase_ : int = True lowercase_ : Dict = True lowercase_ : int = False lowercase_ : Dict = False lowercase_ : Union[str, Any] = False lowercase_ : List[Any] = 2 lowercase_ : Optional[int] = 99 lowercase_ : List[Any] = 0 lowercase_ : Dict = 32 lowercase_ : List[Any] = 2 lowercase_ : Tuple = 4 lowercase_ : List[Any] = 0.1 lowercase_ : List[Any] = 0.1 lowercase_ : Optional[Any] = 5_12 lowercase_ : Optional[Any] = 16 lowercase_ : List[str] = 2 lowercase_ : str = 0.02 lowercase_ : Any = 3 lowercase_ : List[str] = 4 lowercase_ : Dict = '''last''' lowercase_ : int = True lowercase_ : str = None lowercase_ : Dict = 0 def A ( self : List[str] ) -> List[Any]: lowercase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) lowercase_ : Any = None if self.use_input_lengths: lowercase_ : Optional[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowercase_ : List[Any] = None if self.use_token_type_ids: lowercase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowercase_ : Optional[int] = None lowercase_ : str = None lowercase_ : Optional[Any] = None if self.use_labels: lowercase_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase_ : Optional[int] = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) lowercase_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) lowercase_ : Any = FlaubertConfig( 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 , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def A ( self : int , A : Dict , A : Dict , A : str , A : Tuple , A : Optional[Any] , A : str , A : Union[str, Any] , A : Dict , A : Optional[int] , ) -> int: lowercase_ : str = TFFlaubertModel(config=A ) lowercase_ : int = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids} lowercase_ : int = model(A ) lowercase_ : Any = [input_ids, input_mask] lowercase_ : Optional[int] = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : Optional[Any] , A : int , A : List[str] , A : Dict , A : int , A : int , A : Dict , A : Optional[int] , A : Dict , A : int , ) -> Optional[Any]: lowercase_ : int = TFFlaubertWithLMHeadModel(A ) lowercase_ : List[Any] = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids} lowercase_ : List[str] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self : List[str] , A : Optional[int] , A : Tuple , A : Dict , A : List[Any] , A : Dict , A : Any , A : List[Any] , A : List[Any] , A : str , ) -> Union[str, Any]: lowercase_ : List[Any] = TFFlaubertForQuestionAnsweringSimple(A ) lowercase_ : Tuple = {'''input_ids''': input_ids, '''lengths''': input_lengths} lowercase_ : List[str] = model(A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self : int , A : Optional[Any] , A : int , A : List[str] , A : Optional[Any] , A : Tuple , A : Dict , A : Any , A : Any , A : str , ) -> Optional[int]: lowercase_ : str = TFFlaubertForSequenceClassification(A ) lowercase_ : Any = {'''input_ids''': input_ids, '''lengths''': input_lengths} lowercase_ : Union[str, Any] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A ( self : List[Any] , A : Tuple , A : int , A : Dict , A : Any , A : int , A : Optional[int] , A : str , A : str , A : int , ) -> Optional[int]: lowercase_ : Optional[Any] = self.num_labels lowercase_ : List[Any] = TFFlaubertForTokenClassification(config=A ) lowercase_ : int = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowercase_ : int = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : List[str] , A : str , A : Any , A : int , A : Dict , A : Tuple , A : List[Any] , A : Optional[Any] , A : List[Any] , A : Optional[int] , ) -> Union[str, Any]: lowercase_ : Union[str, Any] = self.num_choices lowercase_ : Union[str, Any] = TFFlaubertForMultipleChoice(config=A ) lowercase_ : Union[str, Any] = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) lowercase_ : Any = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) lowercase_ : Dict = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) lowercase_ : Any = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } lowercase_ : Any = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A ( self : Optional[int] ) -> str: lowercase_ : List[Any] = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Dict = config_and_inputs lowercase_ : Optional[int] = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''langs''': token_type_ids, '''lengths''': input_lengths, } return config, inputs_dict @require_tf class _UpperCAmelCase ( _A , _A , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) SCREAMING_SNAKE_CASE_ : Dict = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Optional[Any] = False def A ( self : Any , A : Any , A : Union[str, Any] , A : Optional[int] , A : int , A : str ) -> Any: 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 : Any ) -> Optional[int]: lowercase_ : Dict = TFFlaubertModelTester(self ) lowercase_ : Optional[Any] = ConfigTester(self , config_class=A , emb_dim=37 ) def A ( self : List[str] ) -> Dict: self.config_tester.run_common_tests() def A ( self : List[str] ) -> int: lowercase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*A ) def A ( self : List[str] ) -> int: lowercase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*A ) def A ( self : List[str] ) -> int: lowercase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*A ) def A ( self : Any ) -> List[Any]: lowercase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*A ) def A ( self : Optional[int] ) -> str: lowercase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*A ) def A ( self : Optional[Any] ) -> Tuple: lowercase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*A ) @slow def A ( self : List[Any] ) -> Optional[Any]: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ : Tuple = TFFlaubertModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_tf @require_sentencepiece @require_tokenizers class _UpperCAmelCase ( unittest.TestCase ): @slow def A ( self : str ) -> int: lowercase_ : Any = TFFlaubertModel.from_pretrained('''jplu/tf-flaubert-small-cased''' ) lowercase_ : Optional[int] = tf.convert_to_tensor( [[0, 1_58, 7_35, 25_92, 14_24, 67_27, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" lowercase_ : int = model(A )[0] lowercase_ : str = tf.TensorShape((1, 8, 5_12) ) self.assertEqual(output.shape , A ) # compare the actual values for a slice. lowercase_ : int = tf.convert_to_tensor( [ [ [-1.8768773, -1.566555, 0.27072418], [-1.6920038, -0.5873505, 1.9329599], [-2.9563985, -1.6993835, 1.7972052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
33
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( 'kwargs, expected', [ ({'num_shards': 0, 'max_num_jobs': 1}, []), ({'num_shards': 10, 'max_num_jobs': 1}, [range(10 )]), ({'num_shards': 10, 'max_num_jobs': 10}, [range(lowerCAmelCase_, i + 1 ) for i in range(10 )]), ({'num_shards': 1, 'max_num_jobs': 10}, [range(1 )]), ({'num_shards': 10, 'max_num_jobs': 3}, [range(0, 4 ), range(4, 7 ), range(7, 10 )]), ({'num_shards': 3, 'max_num_jobs': 10}, [range(0, 1 ), range(1, 2 ), range(2, 3 )]), ], ) def a_ ( lowerCAmelCase_ : Optional[Any], lowerCAmelCase_ : Any ): __lowerCAmelCase = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( 'gen_kwargs, max_num_jobs, expected', [ ({'foo': 0}, 10, [{'foo': 0}]), ({'shards': [0, 1, 2, 3]}, 1, [{'shards': [0, 1, 2, 3]}]), ({'shards': [0, 1, 2, 3]}, 4, [{'shards': [0]}, {'shards': [1]}, {'shards': [2]}, {'shards': [3]}]), ({'shards': [0, 1]}, 4, [{'shards': [0]}, {'shards': [1]}]), ({'shards': [0, 1, 2, 3]}, 2, [{'shards': [0, 1]}, {'shards': [2, 3]}]), ], ) def a_ ( lowerCAmelCase_ : Optional[Any], lowerCAmelCase_ : List[str], lowerCAmelCase_ : Optional[int] ): __lowerCAmelCase = _split_gen_kwargs(lowerCAmelCase_, lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( 'gen_kwargs, expected', [ ({'foo': 0}, 1), ({'shards': [0]}, 1), ({'shards': [0, 1, 2, 3]}, 4), ({'shards': [0, 1, 2, 3], 'foo': 0}, 4), ({'shards': [0, 1, 2, 3], 'other': (0, 1)}, 4), ({'shards': [0, 1, 2, 3], 'shards2': [0, 1]}, RuntimeError), ], ) def a_ ( lowerCAmelCase_ : int, lowerCAmelCase_ : Any ): if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __lowerCAmelCase = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
284
0
"""simple docstring""" def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> int: return 1 if input_a == input_a else 0 def UpperCAmelCase ( ) -> None: assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
361
"""simple docstring""" from __future__ import annotations import math def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> int: if depth < 0: raise ValueError('Depth cannot be less than 0' ) if len(UpperCAmelCase ) == 0: raise ValueError('Scores cannot be empty' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , ) return min( minimax(depth + 1 , node_index * 2 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , ) def UpperCAmelCase ( ) -> None: snake_case_ = [90, 23, 6, 33, 21, 65, 123, 34423] snake_case_ = math.log(len(UpperCAmelCase ) , 2 ) print('Optimal value : ' , end='' ) print(minimax(0 , 0 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
312
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class A ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = FlaxAutoencoderKL @property def snake_case__ ( self : Any )-> int: '''simple docstring''' A__ = 4 A__ = 3 A__ = (3_2, 3_2) A__ = jax.random.PRNGKey(0 ) A__ = jax.random.uniform(lowercase_,((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def snake_case__ ( self : Any )-> str: '''simple docstring''' A__ = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } A__ = self.dummy_input return init_dict, inputs_dict
7
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = 'open-llama' def __init__( self : Any,lowercase_ : Optional[int]=1_0_0_0_0_0,lowercase_ : Union[str, Any]=4_0_9_6,lowercase_ : Dict=1_1_0_0_8,lowercase_ : Dict=3_2,lowercase_ : Optional[int]=3_2,lowercase_ : Dict="silu",lowercase_ : Union[str, Any]=2_0_4_8,lowercase_ : Optional[int]=0.02,lowercase_ : Dict=1E-6,lowercase_ : Dict=True,lowercase_ : List[Any]=0,lowercase_ : Optional[int]=1,lowercase_ : str=2,lowercase_ : str=False,lowercase_ : str=True,lowercase_ : int=0.1,lowercase_ : List[Any]=0.1,lowercase_ : List[Any]=True,lowercase_ : Union[str, Any]=True,lowercase_ : Any=None,**lowercase_ : List[Any],)-> Tuple: '''simple docstring''' A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = intermediate_size A__ = num_hidden_layers A__ = num_attention_heads A__ = hidden_act A__ = initializer_range A__ = rms_norm_eps A__ = use_cache A__ = kwargs.pop( 'use_memorry_efficient_attention',lowercase_ ) A__ = hidden_dropout_prob A__ = attention_dropout_prob A__ = use_stable_embedding A__ = shared_input_output_embedding A__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=lowercase_,bos_token_id=lowercase_,eos_token_id=lowercase_,tie_word_embeddings=lowercase_,**lowercase_,) def snake_case__ ( self : str )-> str: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling,lowercase_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F'got {self.rope_scaling}' ) A__ = self.rope_scaling.get('type',lowercase_ ) A__ = self.rope_scaling.get('factor',lowercase_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(lowercase_,lowercase_ ) or rope_scaling_factor <= 1.0: raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
7
1
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class SCREAMING_SNAKE_CASE__ : A_ : torch.Tensor # [batch_size x 3] A_ : torch.Tensor # [batch_size x 3] A_ : torch.Tensor # [batch_size x 3] A_ : torch.Tensor # [batch_size x 3] A_ : int A_ : int A_ : float A_ : float A_ : Tuple[int] def a (self : List[str] ): """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a (self : Optional[int] ): """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a (self : Optional[int] ): """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a (self : List[Any] ): """simple docstring""" __snake_case = torch.arange(self.height * self.width ) __snake_case = torch.stack( [ pixel_indices % self.width, torch.div(a__ , self.width , rounding_mode='''trunc''' ), ] , axis=1 , ) return coords @property def a (self : Optional[int] ): """simple docstring""" __snake_case , *__snake_case = self.shape __snake_case = int(np.prod(a__ ) ) __snake_case = self.get_image_coords() __snake_case = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __snake_case = self.get_camera_rays(a__ ) __snake_case = rays.view(a__ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a (self : Optional[int] , a__ : torch.Tensor ): """simple docstring""" __snake_case , *__snake_case , __snake_case = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __snake_case = coords.view(a__ , -1 , 2 ) __snake_case = self.resolution() __snake_case = self.fov() __snake_case = (flat.float() / (res - 1)) * 2 - 1 __snake_case = fracs * torch.tan(fov / 2 ) __snake_case = fracs.view(a__ , -1 , 2 ) __snake_case = ( self.z.view(a__ , 1 , 3 ) + self.x.view(a__ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a__ , 1 , 3 ) * fracs[:, :, 1:] ) __snake_case = directions / directions.norm(dim=-1 , keepdim=a__ ) __snake_case = torch.stack( [ torch.broadcast_to(self.origin.view(a__ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a__ , *a__ , 2 , 3 ) def a (self : Any , a__ : int , a__ : int ): """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a__ , height=a__ , x_fov=self.x_fov , y_fov=self.y_fov , ) def lowerCamelCase__ ( snake_case_ : int ) -> DifferentiableProjectiveCamera: __snake_case = [] __snake_case = [] __snake_case = [] __snake_case = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): __snake_case = np.array([np.sin(snake_case_ ), np.cos(snake_case_ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __snake_case = -z * 4 __snake_case = np.array([np.cos(snake_case_ ), -np.sin(snake_case_ ), 0.0] ) __snake_case = np.cross(snake_case_ , snake_case_ ) origins.append(snake_case_ ) xs.append(snake_case_ ) ys.append(snake_case_ ) zs.append(snake_case_ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(snake_case_ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(snake_case_ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(snake_case_ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(snake_case_ , axis=0 ) ).float() , width=snake_case_ , height=snake_case_ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(snake_case_ )) , )
361
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
238
0
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a (UpperCamelCase__ ): """simple docstring""" def __init__( self : Any , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : DDIMScheduler ) -> str: super().__init__() self.register_modules(vqvae=__lowerCamelCase , unet=__lowerCamelCase , scheduler=__lowerCamelCase ) @torch.no_grad() def __call__( self : Optional[Any] , lowerCamelCase : int = 1 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : float = 0.0 , lowerCamelCase : int = 50 , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , **lowerCamelCase : Dict , ) -> List[Any]: __snake_case : str = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=__lowerCamelCase , ) __snake_case : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __snake_case : Optional[Any] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(__lowerCamelCase ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature __snake_case : Dict = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(self.scheduler.timesteps ): __snake_case : List[Any] = self.scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase ) # predict the noise residual __snake_case : Union[str, Any] = self.unet(__lowerCamelCase , __lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : str = self.scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample # decode the image latents with the VAE __snake_case : Any = self.vqvae.decode(__lowerCamelCase ).sample __snake_case : Tuple = (image / 2 + 0.5).clamp(0 , 1 ) __snake_case : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : List[Any] = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCamelCase )
123
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def lowerCAmelCase_ ( A_ ,A_ ,A_): UpperCamelCase__: Dict = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") UpperCamelCase__: Dict = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(A_): os.makedirs(A_) UpperCamelCase__: Optional[Any] = model.state_dict() def to_tf_var_name(A_): for patt, repl in iter(A_): UpperCamelCase__: Optional[Any] = name.replace(A_ ,A_) return F"bert/{name}" def create_tf_var(A_ ,A_ ,A_): UpperCamelCase__: Any = tf.dtypes.as_dtype(tensor.dtype) UpperCamelCase__: int = tf.get_variable(dtype=A_ ,shape=tensor.shape ,name=A_ ,initializer=tf.zeros_initializer()) session.run(tf.variables_initializer([tf_var])) session.run(A_) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: UpperCamelCase__: List[Any] = to_tf_var_name(A_) UpperCamelCase__: List[str] = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose): UpperCamelCase__: List[Any] = torch_tensor.T UpperCamelCase__: int = create_tf_var(tensor=A_ ,name=A_ ,session=A_) tf.keras.backend.set_value(A_ ,A_) UpperCamelCase__: Optional[Any] = session.run(A_) print(F"Successfully created {tf_name}: {np.allclose(A_ ,A_)}") UpperCamelCase__: Tuple = tf.train.Saver(tf.trainable_variables()) saver.save(A_ ,os.path.join(A_ ,model_name.replace("-" ,"_") + ".ckpt")) def lowerCAmelCase_ ( A_=None): UpperCamelCase__: Tuple = argparse.ArgumentParser() parser.add_argument("--model_name" ,type=A_ ,required=A_ ,help="model name e.g. bert-base-uncased") parser.add_argument( "--cache_dir" ,type=A_ ,default=A_ ,required=A_ ,help="Directory containing pytorch model") parser.add_argument("--pytorch_model_path" ,type=A_ ,required=A_ ,help="/path/to/<pytorch-model-name>.bin") parser.add_argument("--tf_cache_dir" ,type=A_ ,required=A_ ,help="Directory in which to save tensorflow model") UpperCamelCase__: Any = parser.parse_args(A_) UpperCamelCase__: List[Any] = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name ,state_dict=torch.load(args.pytorch_model_path) ,cache_dir=args.cache_dir ,) convert_pytorch_checkpoint_to_tf(model=A_ ,ckpt_dir=args.tf_cache_dir ,model_name=args.model_name) if __name__ == "__main__": main()
149
0
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
352
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : 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 UpperCAmelCase__ : 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 lowerCamelCase__ ( a , a , a , a ) -> 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 lowerCamelCase__ ( a ) -> 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 lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , 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' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
0
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowercase : List[Any] = logging.get_logger(__name__) lowercase : Optional[int] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} lowercase : List[Any] = { """vocab_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json""" }, """merges_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt""" }, } lowercase : Any = {"""allegro/herbert-base-cased""": 5_1_4} lowercase : str = {} class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Any = VOCAB_FILES_NAMES __A : str = PRETRAINED_VOCAB_FILES_MAP __A : Optional[int] = PRETRAINED_INIT_CONFIGURATION __A : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __A : Tuple = HerbertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=None , lowercase="<s>" , lowercase="<unk>" , lowercase="<pad>" , lowercase="<mask>" , lowercase="</s>" , **lowercase , ) -> List[Any]: '''simple docstring''' super().__init__( lowercase , lowercase , tokenizer_file=lowercase , cls_token=lowercase , unk_token=lowercase , pad_token=lowercase , mask_token=lowercase , sep_token=lowercase , **lowercase , ) def __lowercase ( self , lowercase , lowercase = None) -> List[int]: '''simple docstring''' a__ : str = [self.cls_token_id] a__ : Tuple = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowercase ( self , lowercase , lowercase = None , lowercase = False) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase , token_ids_a=lowercase , already_has_special_tokens=lowercase) if token_ids_a is None: return [1] + ([0] * len(lowercase)) + [1] return [1] + ([0] * len(lowercase)) + [1] + ([0] * len(lowercase)) + [1] def __lowercase ( self , lowercase , lowercase = None) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def __lowercase ( self , lowercase , lowercase = None) -> Tuple[str]: '''simple docstring''' a__ : Any = self._tokenizer.model.save(lowercase , name=lowercase) return tuple(lowercase)
99
import os import sys import unittest UpperCAmelCase__ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path UpperCAmelCase__ = os.path.join(git_repo_path, "src", "diffusers") class __lowerCAmelCase ( unittest.TestCase ): def _lowerCamelCase ( self : Tuple) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = find_backend(' if not is_torch_available():') self.assertEqual(A , 'torch') # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") _UpperCAmelCase = find_backend(' if not (is_torch_available() and is_transformers_available()):') self.assertEqual(A , 'torch_and_transformers') # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") _UpperCAmelCase = find_backend( ' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):') self.assertEqual(A , 'torch_and_transformers_and_onnx') def _lowerCamelCase ( self : int) -> Dict: """simple docstring""" _UpperCAmelCase = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , A) self.assertIn('torch_and_transformers' , A) self.assertIn('flax_and_transformers' , A) self.assertIn('torch_and_transformers_and_onnx' , A) # Likewise, we can't assert on the exact content of a key self.assertIn('UNet2DModel' , objects['torch']) self.assertIn('FlaxUNet2DConditionModel' , objects['flax']) self.assertIn('StableDiffusionPipeline' , objects['torch_and_transformers']) self.assertIn('FlaxStableDiffusionPipeline' , objects['flax_and_transformers']) self.assertIn('LMSDiscreteScheduler' , objects['torch_and_scipy']) self.assertIn('OnnxStableDiffusionPipeline' , objects['torch_and_transformers_and_onnx']) def _lowerCamelCase ( self : Union[str, Any]) -> List[Any]: """simple docstring""" _UpperCAmelCase = create_dummy_object('CONSTANT' , '\'torch\'') self.assertEqual(A , '\nCONSTANT = None\n') _UpperCAmelCase = create_dummy_object('function' , '\'torch\'') self.assertEqual( A , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n') _UpperCAmelCase = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n' _UpperCAmelCase = create_dummy_object('FakeClass' , '\'torch\'') self.assertEqual(A , A) def _lowerCamelCase ( self : Dict) -> int: """simple docstring""" _UpperCAmelCase = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n' _UpperCAmelCase = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}) self.assertEqual(dummy_files['torch'] , A)
339
0
'''simple docstring''' import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( lowerCamelCase_ :Tuple , lowerCamelCase_ :Tuple , lowerCamelCase_ :Tuple ): '''simple docstring''' snake_case_ : Optional[int] = TaConfig.from_json_file(_lowerCAmelCase ) print(F'''Building PyTorch model from configuration: {config}''' ) snake_case_ : Optional[int] = TaForConditionalGeneration(_lowerCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_ta(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __A : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
353
'''simple docstring''' from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A : Tuple = logging.get_logger(__name__) class __UpperCamelCase ( lowercase__ ): lowercase : str = ['input_values', 'padding_mask'] def __init__( self :Optional[int] ,_UpperCamelCase :int = 1 ,_UpperCamelCase :int = 2_4_0_0_0 ,_UpperCamelCase :float = 0.0 ,_UpperCamelCase :float = None ,_UpperCamelCase :float = None ,**_UpperCamelCase :List[Any] ,): super().__init__(feature_size=_UpperCamelCase ,sampling_rate=_UpperCamelCase ,padding_value=_UpperCamelCase ,**_UpperCamelCase ) snake_case_ : Dict = chunk_length_s snake_case_ : str = overlap @property def a__ ( self :Any ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def a__ ( self :List[str] ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 ,int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self :Optional[Any] ,_UpperCamelCase :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,_UpperCamelCase :Optional[Union[bool, str, PaddingStrategy]] = None ,_UpperCamelCase :Optional[bool] = False ,_UpperCamelCase :Optional[int] = None ,_UpperCamelCase :Optional[Union[str, TensorType]] = None ,_UpperCamelCase :Optional[int] = None ,): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) if padding and truncation: raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" ) elif padding is None: # by default let's pad the inputs snake_case_ : Tuple = True snake_case_ : str = bool( isinstance(_UpperCamelCase ,(list, tuple) ) and (isinstance(raw_audio[0] ,(np.ndarray, tuple, list) )) ) if is_batched: snake_case_ : Any = [np.asarray(_UpperCamelCase ,dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(_UpperCamelCase ,np.ndarray ): snake_case_ : Optional[int] = np.asarray(_UpperCamelCase ,dtype=np.floataa ) elif isinstance(_UpperCamelCase ,np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): snake_case_ : List[str] = raw_audio.astype(np.floataa ) # always return batch if not is_batched: snake_case_ : Optional[Any] = [np.asarray(_UpperCamelCase ).T] # verify inputs are valid for idx, example in enumerate(_UpperCamelCase ): if example.ndim > 2: raise ValueError(F'''Expected input shape (channels, length) but got shape {example.shape}''' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(F'''Expected mono audio but example has {example.shape[-1]} channels''' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(F'''Expected stereo audio but example has {example.shape[-1]} channels''' ) snake_case_ : Tuple = None snake_case_ : Optional[Any] = BatchFeature({"""input_values""": raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: snake_case_ : Union[str, Any] = min(array.shape[0] for array in raw_audio ) snake_case_ : Dict = int(np.floor(max_length / self.chunk_stride ) ) snake_case_ : Union[str, Any] = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: snake_case_ : Any = max(array.shape[0] for array in raw_audio ) snake_case_ : List[Any] = int(np.ceil(max_length / self.chunk_stride ) ) snake_case_ : Any = (nb_step - 1) * self.chunk_stride + self.chunk_length snake_case_ : Union[str, Any] = """max_length""" else: snake_case_ : int = input_values # normal padding on batch if padded_inputs is None: snake_case_ : Optional[int] = self.pad( _UpperCamelCase ,max_length=_UpperCamelCase ,truncation=_UpperCamelCase ,padding=_UpperCamelCase ,return_attention_mask=_UpperCamelCase ,) if padding: snake_case_ : Tuple = padded_inputs.pop("""attention_mask""" ) snake_case_ : Optional[int] = [] for example in padded_inputs.pop("""input_values""" ): if self.feature_size == 1: snake_case_ : Dict = example[..., None] input_values.append(example.T ) snake_case_ : List[Any] = input_values if return_tensors is not None: snake_case_ : Tuple = padded_inputs.convert_to_tensors(_UpperCamelCase ) return padded_inputs
8
0
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __a : Tuple = logging.get_logger(__name__) __a : Union[str, Any] = { "nielsr/canine-s": 2_0_4_8, } # Unicode defines 1,114,112 total “codepoints” __a : Optional[int] = 1_1_1_4_1_1_2 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py __a : List[str] = 0 __a : int = 0Xe_0_0_0 __a : Any = 0Xe_0_0_1 __a : List[Any] = 0Xe_0_0_2 __a : Union[str, Any] = 0Xe_0_0_3 __a : List[str] = 0Xe_0_0_4 # Maps special codepoints to human-readable names. __a : Dict[int, str] = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. __a : Dict[str, int] = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class _UpperCamelCase ( _UpperCAmelCase ): """simple docstring""" __a : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=chr(lowerCAmelCase__ ) , lowerCAmelCase__=False , lowerCAmelCase__=20_48 , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else bos_token __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else eos_token __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else sep_token __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else cls_token __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowercase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , model_max_length=lowerCAmelCase__ , **lowerCAmelCase__ , ) # Creates a mapping for looking up the IDs of special symbols. __lowercase = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): __lowercase = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. __lowercase = { codepoint: name for name, codepoint in self._special_codepoints.items() } __lowercase = UNICODE_VOCAB_SIZE __lowercase = len(self._special_codepoints ) @property def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' return self._unicode_vocab_size def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' return list(lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> int: '''simple docstring''' try: return ord(lowerCAmelCase__ ) except TypeError: raise ValueError(F"invalid token: \'{token}\'" ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(lowerCAmelCase__ ) except TypeError: raise ValueError(F"invalid id: {index}" ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' return "".join(lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Optional[Any]: '''simple docstring''' __lowercase = [self.sep_token_id] __lowercase = [self.cls_token_id] __lowercase = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> Optional[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase__ , token_ids_a=lowerCAmelCase__ , already_has_special_tokens=lowerCAmelCase__ ) __lowercase = [1] + ([0] * len(lowerCAmelCase__ )) + [1] if token_ids_a is not None: result += ([0] * len(lowerCAmelCase__ )) + [1] return result def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Union[str, Any]: '''simple docstring''' __lowercase = [self.sep_token_id] __lowercase = [self.cls_token_id] __lowercase = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> int: '''simple docstring''' return ()
210
def __A ( __lowerCamelCase ) -> int: a = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __A ( __lowerCamelCase = 100 ) -> int: a = 1 a = 2 for i in range(2 , max_n + 1 ): a = pre_numerator a = 2 * i // 3 if i % 3 == 0 else 1 a = cur_numerator a = e_cont * pre_numerator + temp return sum_digits(__lowerCamelCase ) if __name__ == "__main__": print(F'{solution() = }')
228
0
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants UpperCamelCase__ = Mapping[str, np.ndarray] UpperCamelCase__ = Mapping[str, Any] # Is a nested dict. UpperCamelCase__ = 0.0_1 @dataclasses.dataclass(frozen=_a ) class A : __UpperCAmelCase : List[str] = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. __UpperCAmelCase : List[Any] = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. __UpperCAmelCase : List[str] = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. __UpperCAmelCase : List[Any] = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. __UpperCAmelCase : Any = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions __UpperCAmelCase : Optional[Any] = None # Optional remark about the protein. Included as a comment in output PDB # files __UpperCAmelCase : int = None # Templates used to generate this protein (prediction-only) __UpperCAmelCase : Optional[Any] = None # Chain corresponding to each parent __UpperCAmelCase : Tuple = None def lowerCAmelCase_ ( __A ) -> Protein: '''simple docstring''' UpperCAmelCase__ = r"""(\[[A-Z]+\]\n)""" UpperCAmelCase__ = [tag.strip() for tag in re.split(_lowerCAmelCase, _lowerCAmelCase ) if len(_lowerCAmelCase ) > 0] UpperCAmelCase__ = zip(tags[0::2], [l.split("\n" ) for l in tags[1::2]] ) UpperCAmelCase__ = ["N", "CA", "C"] UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None for g in groups: if "[PRIMARY]" == g[0]: UpperCAmelCase__ = g[1][0].strip() for i in range(len(_lowerCAmelCase ) ): if seq[i] not in residue_constants.restypes: UpperCAmelCase__ = """X""" # FIXME: strings are immutable UpperCAmelCase__ = np.array( [residue_constants.restype_order.get(_lowerCAmelCase, residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: UpperCAmelCase__ = [] for axis in range(3 ): tertiary.append(list(map(_lowerCAmelCase, g[1][axis].split() ) ) ) UpperCAmelCase__ = np.array(_lowerCAmelCase ) UpperCAmelCase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(_lowerCAmelCase ): UpperCAmelCase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: UpperCAmelCase__ = np.array(list(map({"-": 0, "+": 1}.get, g[1][0].strip() ) ) ) UpperCAmelCase__ = np.zeros( ( len(_lowerCAmelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(_lowerCAmelCase ): UpperCAmelCase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=_lowerCAmelCase, atom_mask=_lowerCAmelCase, aatype=_lowerCAmelCase, residue_index=np.arange(len(_lowerCAmelCase ) ), b_factors=_lowerCAmelCase, ) def lowerCAmelCase_ ( __A, __A = 0 ) -> List[str]: '''simple docstring''' UpperCAmelCase__ = [] UpperCAmelCase__ = prot.remark if remark is not None: pdb_headers.append(f"""REMARK {remark}""" ) UpperCAmelCase__ = prot.parents UpperCAmelCase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: UpperCAmelCase__ = [p for i, p in zip(_lowerCAmelCase, _lowerCAmelCase ) if i == chain_id] if parents is None or len(_lowerCAmelCase ) == 0: UpperCAmelCase__ = ["""N/A"""] pdb_headers.append(f"""PARENT {" ".join(_lowerCAmelCase )}""" ) return pdb_headers def lowerCAmelCase_ ( __A, __A ) -> str: '''simple docstring''' UpperCAmelCase__ = [] UpperCAmelCase__ = pdb_str.split("\n" ) UpperCAmelCase__ = prot.remark if remark is not None: out_pdb_lines.append(f"""REMARK {remark}""" ) UpperCAmelCase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: UpperCAmelCase__ = [] if prot.parents_chain_index is not None: UpperCAmelCase__ = {} for p, i in zip(prot.parents, prot.parents_chain_index ): parent_dict.setdefault(str(_lowerCAmelCase ), [] ) parent_dict[str(_lowerCAmelCase )].append(_lowerCAmelCase ) UpperCAmelCase__ = max([int(_lowerCAmelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): UpperCAmelCase__ = parent_dict.get(str(_lowerCAmelCase ), ["N/A"] ) parents_per_chain.append(_lowerCAmelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: UpperCAmelCase__ = [["""N/A"""]] def make_parent_line(__A ) -> str: return f"""PARENT {" ".join(_lowerCAmelCase )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) UpperCAmelCase__ = 0 for i, l in enumerate(_lowerCAmelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(_lowerCAmelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(_lowerCAmelCase ): UpperCAmelCase__ = parents_per_chain[chain_counter] else: UpperCAmelCase__ = ["""N/A"""] out_pdb_lines.append(make_parent_line(_lowerCAmelCase ) ) return "\n".join(_lowerCAmelCase ) def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' UpperCAmelCase__ = residue_constants.restypes + ["""X"""] def res_atoa(__A ) -> str: return residue_constants.restype_atoa.get(restypes[r], "UNK" ) UpperCAmelCase__ = residue_constants.atom_types UpperCAmelCase__ = [] UpperCAmelCase__ = prot.atom_mask UpperCAmelCase__ = prot.aatype UpperCAmelCase__ = prot.atom_positions UpperCAmelCase__ = prot.residue_index.astype(np.intaa ) UpperCAmelCase__ = prot.b_factors UpperCAmelCase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("Invalid aatypes." ) UpperCAmelCase__ = get_pdb_headers(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: pdb_lines.extend(_lowerCAmelCase ) UpperCAmelCase__ = aatype.shape[0] UpperCAmelCase__ = 1 UpperCAmelCase__ = 0 UpperCAmelCase__ = string.ascii_uppercase UpperCAmelCase__ = None # Add all atom sites. for i in range(_lowerCAmelCase ): UpperCAmelCase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(_lowerCAmelCase, atom_positions[i], atom_mask[i], b_factors[i] ): if mask < 0.5: continue UpperCAmelCase__ = """ATOM""" UpperCAmelCase__ = atom_name if len(_lowerCAmelCase ) == 4 else f""" {atom_name}""" UpperCAmelCase__ = """""" UpperCAmelCase__ = """""" UpperCAmelCase__ = 1.00 UpperCAmelCase__ = atom_name[0] # Protein supports only C, N, O, S, this works. UpperCAmelCase__ = """""" UpperCAmelCase__ = """A""" if chain_index is not None: UpperCAmelCase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! UpperCAmelCase__ = ( f"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" f"""{res_name_a:>3} {chain_tag:>1}""" f"""{residue_index[i]:>4}{insertion_code:>1} """ f"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" f"""{occupancy:>6.2f}{b_factor:>6.2f} """ f"""{element:>2}{charge:>2}""" ) pdb_lines.append(_lowerCAmelCase ) atom_index += 1 UpperCAmelCase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: UpperCAmelCase__ = True UpperCAmelCase__ = chain_index[i + 1] if should_terminate: # Close the chain. UpperCAmelCase__ = """TER""" UpperCAmelCase__ = ( f"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(_lowerCAmelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(_lowerCAmelCase, _lowerCAmelCase ) ) pdb_lines.append("END" ) pdb_lines.append("" ) return "\n".join(_lowerCAmelCase ) def lowerCAmelCase_ ( __A ) -> np.ndarray: '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def lowerCAmelCase_ ( __A, __A, __A = None, __A = None, __A = None, __A = None, __A = None, ) -> Protein: '''simple docstring''' return Protein( aatype=features["aatype"], atom_positions=result["final_atom_positions"], atom_mask=result["final_atom_mask"], residue_index=features["residue_index"] + 1, b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"] ), chain_index=_lowerCAmelCase, remark=_lowerCAmelCase, parents=_lowerCAmelCase, parents_chain_index=_lowerCAmelCase, )
371
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( "compression_format, is_archive", [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ], ) def lowerCAmelCase_ ( __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, ) -> Any: '''simple docstring''' UpperCAmelCase__ = { "7z": (seven_zip_file, SevenZipExtractor), "bz2": (bza_file, BzipaExtractor), "gzip": (gz_file, GzipExtractor), "lz4": (lza_file, LzaExtractor), "tar": (tar_file, TarExtractor), "xz": (xz_file, XzExtractor), "zip": (zip_file, ZipExtractor), "zstd": (zstd_file, ZstdExtractor), } UpperCAmelCase__ , UpperCAmelCase__ = input_paths_and_base_extractors[compression_format] if input_path is None: UpperCAmelCase__ = f"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__A ) assert base_extractor.is_extractable(__A ) UpperCAmelCase__ = tmp_path / ("extracted" if is_archive else "extracted.txt") base_extractor.extract(__A, __A ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name UpperCAmelCase__ = file_path.read_text(encoding="utf-8" ) else: UpperCAmelCase__ = output_path.read_text(encoding="utf-8" ) UpperCAmelCase__ = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( "compression_format, is_archive", [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ], ) def lowerCAmelCase_ ( __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, __A, ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = { "7z": seven_zip_file, "bz2": bza_file, "gzip": gz_file, "lz4": lza_file, "tar": tar_file, "xz": xz_file, "zip": zip_file, "zstd": zstd_file, } UpperCAmelCase__ = input_paths[compression_format] if input_path is None: UpperCAmelCase__ = f"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__A ) UpperCAmelCase__ = Extractor.infer_extractor_format(__A ) assert extractor_format is not None UpperCAmelCase__ = tmp_path / ("extracted" if is_archive else "extracted.txt") Extractor.extract(__A, __A, __A ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name UpperCAmelCase__ = file_path.read_text(encoding="utf-8" ) else: UpperCAmelCase__ = output_path.read_text(encoding="utf-8" ) UpperCAmelCase__ = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.fixture def lowerCAmelCase_ ( __A, __A ) -> List[str]: '''simple docstring''' import tarfile UpperCAmelCase__ = tmp_path / "data_dot_dot" directory.mkdir() UpperCAmelCase__ = directory / "tar_file_with_dot_dot.tar" with tarfile.TarFile(__A, "w" ) as f: f.add(__A, arcname=os.path.join("..", text_file.name ) ) return path @pytest.fixture def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' import tarfile UpperCAmelCase__ = tmp_path / "data_sym_link" directory.mkdir() UpperCAmelCase__ = directory / "tar_file_with_sym_link.tar" os.symlink("..", directory / "subdir", target_is_directory=__A ) with tarfile.TarFile(__A, "w" ) as f: f.add(str(directory / "subdir" ), arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( "insecure_tar_file, error_log", [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")], ) def lowerCAmelCase_ ( __A, __A, __A, __A, __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = { "tar_file_with_dot_dot": tar_file_with_dot_dot, "tar_file_with_sym_link": tar_file_with_sym_link, } UpperCAmelCase__ = insecure_tar_files[insecure_tar_file] UpperCAmelCase__ = tmp_path / "extracted" TarExtractor.extract(__A, __A ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def lowerCAmelCase_ ( __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = tmpdir / "not_a_zip_file" # From: https://github.com/python/cpython/pull/5053 UpperCAmelCase__ = ( B"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00" B"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I" B"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07" B"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82" ) with not_a_zip_file.open("wb" ) as f: f.write(__A ) assert zipfile.is_zipfile(str(__A ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(__A ) # but we're right
143
0
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __UpperCamelCase ( _A : Dict , _A : Optional[int] , _A : Tuple ) ->Union[str, Any]: """simple docstring""" if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , _A ) lowerCamelCase_ =datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: lowerCamelCase_ =dataset_size < in_memory_max_size else: lowerCamelCase_ =False lowerCamelCase_ =is_small_dataset(_A ) assert result == expected
154
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __A : Tuple = logging.get_logger(__name__) def __UpperCamelCase ( _A : str , _A : str , _A : str ) ->int: """simple docstring""" lowerCamelCase_ =UniSpeechSatForSequenceClassification.from_pretrained(_A , config=_A ) lowerCamelCase_ =downstream_dict["""projector.weight"""] lowerCamelCase_ =downstream_dict["""projector.bias"""] lowerCamelCase_ =downstream_dict["""model.post_net.linear.weight"""] lowerCamelCase_ =downstream_dict["""model.post_net.linear.bias"""] return model def __UpperCamelCase ( _A : Optional[int] , _A : str , _A : Any ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =UniSpeechSatForAudioFrameClassification.from_pretrained(_A , config=_A ) lowerCamelCase_ =downstream_dict["""model.linear.weight"""] lowerCamelCase_ =downstream_dict["""model.linear.bias"""] return model def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[Any] , _A : Optional[Any] ) ->List[Any]: """simple docstring""" lowerCamelCase_ =UniSpeechSatForXVector.from_pretrained(_A , config=_A ) lowerCamelCase_ =downstream_dict["""connector.weight"""] lowerCamelCase_ =downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): lowerCamelCase_ =downstream_dict[ f'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] lowerCamelCase_ =downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias'] lowerCamelCase_ =downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] lowerCamelCase_ =downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] lowerCamelCase_ =downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] lowerCamelCase_ =downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] lowerCamelCase_ =downstream_dict["""objective.W"""] return model @torch.no_grad() def __UpperCamelCase ( _A : Any , _A : Optional[Any] , _A : Union[str, Any] , _A : str ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =torch.load(_A , map_location="""cpu""" ) lowerCamelCase_ =checkpoint["""Downstream"""] lowerCamelCase_ =UniSpeechSatConfig.from_pretrained(_A ) lowerCamelCase_ =WavaVecaFeatureExtractor.from_pretrained( _A , return_attention_mask=_A , do_normalize=_A ) lowerCamelCase_ =hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): lowerCamelCase_ =convert_classification(_A , _A , _A ) elif arch.endswith("""ForAudioFrameClassification""" ): lowerCamelCase_ =convert_diarization(_A , _A , _A ) elif arch.endswith("""ForXVector""" ): lowerCamelCase_ =convert_xvector(_A , _A , _A ) else: raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: lowerCamelCase_ =checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(_A ) hf_model.save_pretrained(_A ) if __name__ == "__main__": __A : Optional[int] = 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 : int = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
154
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer __snake_case : int =logging.get_logger(__name__) # pylint: disable=invalid-name __snake_case : Optional[int] ="\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ =42 class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' def __init__(self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,) -> List[Any]: """simple docstring""" super().__init__() self.register_modules( prior=__A ,image_encoder=__A ,image_processor=__A ,scheduler=__A ,renderer=__A ,) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) -> Union[str, Any]: """simple docstring""" if latents is None: lowerCAmelCase__ : Tuple = randn_tensor(__A ,generator=__A ,device=__A ,dtype=__A ) else: if latents.shape != shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) lowerCAmelCase__ : List[str] = latents.to(__A ) lowerCAmelCase__ : Union[str, Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase__ (self ,__lowerCamelCase=0 ) -> Tuple: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) lowerCAmelCase__ : int = torch.device(f"""cuda:{gpu_id}""" ) lowerCAmelCase__ : int = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__A ,__A ) @property def lowerCAmelCase__ (self ) -> Optional[int]: """simple docstring""" if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder ,'''_hf_hook''' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(__A ,'''_hf_hook''' ) and hasattr(module._hf_hook ,'''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,) -> Optional[int]: """simple docstring""" if isinstance(__A ,__A ) and isinstance(image[0] ,torch.Tensor ): lowerCAmelCase__ : Dict = torch.cat(__A ,axis=0 ) if image[0].ndim == 4 else torch.stack(__A ,axis=0 ) if not isinstance(__A ,torch.Tensor ): lowerCAmelCase__ : int = self.image_processor(__A ,return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 ) lowerCAmelCase__ : Dict = image.to(dtype=self.image_encoder.dtype ,device=__A ) lowerCAmelCase__ : int = self.image_encoder(__A )['''last_hidden_state'''] lowerCAmelCase__ : Optional[Any] = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 lowerCAmelCase__ : Union[str, Any] = image_embeds.repeat_interleave(__A ,dim=0 ) if do_classifier_free_guidance: lowerCAmelCase__ : int = torch.zeros_like(__A ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCAmelCase__ : str = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(__A ) def __call__(self ,__lowerCamelCase ,__lowerCamelCase = 1 ,__lowerCamelCase = 25 ,__lowerCamelCase = None ,__lowerCamelCase = None ,__lowerCamelCase = 4.0 ,__lowerCamelCase = 64 ,__lowerCamelCase = "pil" ,__lowerCamelCase = True ,) -> int: """simple docstring""" if isinstance(__A ,PIL.Image.Image ): lowerCAmelCase__ : Tuple = 1 elif isinstance(__A ,torch.Tensor ): lowerCAmelCase__ : Tuple = image.shape[0] elif isinstance(__A ,__A ) and isinstance(image[0] ,(torch.Tensor, PIL.Image.Image) ): lowerCAmelCase__ : Dict = len(__A ) else: raise ValueError( f"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__A )}""" ) lowerCAmelCase__ : Tuple = self._execution_device lowerCAmelCase__ : int = batch_size * num_images_per_prompt lowerCAmelCase__ : str = guidance_scale > 1.0 lowerCAmelCase__ : List[Any] = self._encode_image(__A ,__A ,__A ,__A ) # prior self.scheduler.set_timesteps(__A ,device=__A ) lowerCAmelCase__ : Dict = self.scheduler.timesteps lowerCAmelCase__ : Union[str, Any] = self.prior.config.num_embeddings lowerCAmelCase__ : Optional[int] = self.prior.config.embedding_dim lowerCAmelCase__ : Any = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) ,image_embeds.dtype ,__A ,__A ,__A ,self.scheduler ,) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim lowerCAmelCase__ : List[Any] = latents.reshape(latents.shape[0] ,__A ,__A ) for i, t in enumerate(self.progress_bar(__A ) ): # expand the latents if we are doing classifier free guidance lowerCAmelCase__ : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCAmelCase__ : Optional[Any] = self.scheduler.scale_model_input(__A ,__A ) lowerCAmelCase__ : Any = self.prior( __A ,timestep=__A ,proj_embedding=__A ,).predicted_image_embedding # remove the variance lowerCAmelCase__ : Tuple = noise_pred.split( scaled_model_input.shape[2] ,dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: lowerCAmelCase__ : List[str] = noise_pred.chunk(2 ) lowerCAmelCase__ : int = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) lowerCAmelCase__ : int = self.scheduler.step( __A ,timestep=__A ,sample=__A ,).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=__A ) lowerCAmelCase__ : Union[str, Any] = [] for i, latent in enumerate(__A ): print() lowerCAmelCase__ : Any = self.renderer.decode( latent[None, :] ,__A ,size=__A ,ray_batch_size=40_96 ,n_coarse_samples=64 ,n_fine_samples=1_28 ,) images.append(__A ) lowerCAmelCase__ : Optional[int] = torch.stack(__A ) if output_type not in ["np", "pil"]: raise ValueError(f"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) lowerCAmelCase__ : str = images.cpu().numpy() if output_type == "pil": lowerCAmelCase__ : str = [self.numpy_to_pil(__A ) for image in images] # Offload last model to CPU if hasattr(self ,'''final_offload_hook''' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=__A )
360
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase__ ( lowerCamelCase_ : ndarray): '''simple docstring''' return np.dot(lowerCamelCase_ ,lowerCamelCase_) class lowerCamelCase__ : '''simple docstring''' def __init__(self ,*, __lowerCamelCase = np.inf ,__lowerCamelCase = "linear" ,__lowerCamelCase = 0.0 ,) -> None: """simple docstring""" lowerCAmelCase__ : Any = regularization lowerCAmelCase__ : str = gamma if kernel == "linear": lowerCAmelCase__ : Dict = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma ,(float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) lowerCAmelCase__ : Optional[Any] = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCAmelCase__ : List[str] = f"""Unknown kernel: {kernel}""" raise ValueError(__lowerCamelCase ) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ) -> float: """simple docstring""" return np.dot(__lowerCamelCase ,__lowerCamelCase ) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ) -> float: """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ) -> None: """simple docstring""" lowerCAmelCase__ : str = observations lowerCAmelCase__ : Optional[int] = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCAmelCase__) , ) : List[str] = np.shape(__lowerCamelCase ) def to_minimize(__lowerCamelCase ) -> float: lowerCAmelCase__ : List[str] = 0 ((lowerCAmelCase__) , ) : str = np.shape(__lowerCamelCase ) for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] ,observations[j] ) ) return 1 / 2 * s - sum(__lowerCamelCase ) lowerCAmelCase__ : List[str] = LinearConstraint(__lowerCamelCase ,0 ,0 ) lowerCAmelCase__ : List[str] = Bounds(0 ,self.regularization ) lowerCAmelCase__ : int = minimize( __lowerCamelCase ,np.ones(__lowerCamelCase ) ,bounds=__lowerCamelCase ,constraints=[ly_contraint] ).x lowerCAmelCase__ : List[Any] = l_star # calculating mean offset of separation plane to points lowerCAmelCase__ : Optional[Any] = 0 for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] ,observations[j] ) lowerCAmelCase__ : Dict = s / n def lowerCAmelCase__ (self ,__lowerCamelCase ) -> int: """simple docstring""" lowerCAmelCase__ : str = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] ,__lowerCamelCase ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
94
0
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path _a : List[Any]= '''src/transformers''' # Matches is_xxx_available() _a : Union[str, Any]= re.compile(R"is\_([a-z_]*)_available()") # Catches a one-line _import_struct = {xxx} _a : Optional[Any]= re.compile(R"^_import_structure\s+=\s+\{([^\}]+)\}") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _a : int= re.compile(R"\s+\"\S*\":\s+\[([^\]]*)\]") # Catches a line if not is_foo_available _a : Optional[int]= re.compile(R"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") # Catches a line _import_struct["bla"].append("foo") _a : str= re.compile(R"^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)") # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _a : Optional[int]= re.compile(R"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") # Catches a line with an object between quotes and a comma: "MyModel", _a : Tuple= re.compile("^\s+\"([^\"]+)\",") # Catches a line with objects between brackets only: ["foo", "bar"], _a : Optional[int]= re.compile("^\s+\[([^\]]+)\]") # Catches a line with from foo import bar, bla, boo _a : str= re.compile(R"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") # Catches a line with try: _a : Tuple= re.compile(R"^\s*try:") # Catches a line with else: _a : Tuple= re.compile(R"^\s*else:") def __UpperCAmelCase ( UpperCAmelCase_ : Tuple ) -> Union[str, Any]: '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None __snake_case : Optional[Any] = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> str: '''simple docstring''' with open(A_ , 'r' , encoding='utf-8' , newline='\n' ) as f: __snake_case : Union[str, Any] = f.readlines() __snake_case : Optional[int] = 0 while line_index < len(A_ ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure __snake_case : Optional[int] = [] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: __snake_case : Any = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): __snake_case : Tuple = _re_one_line_import_struct.search(A_ ).groups()[0] __snake_case : int = re.findall('\[([^\]]+)\]' , A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue __snake_case : Dict = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: __snake_case : Union[str, Any] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 __snake_case : Dict = {'''none''': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. __snake_case : Optional[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __snake_case : List[str] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __snake_case : Optional[Any] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): __snake_case : List[str] = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: __snake_case : Dict = _re_import_struct_add_many.search(A_ ).groups()[0].split(', ' ) __snake_case : List[str] = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: __snake_case : Optional[Any] = _re_between_brackets.search(A_ ).groups()[0].split(', ' ) __snake_case : str = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 __snake_case : int = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __snake_case : Optional[Any] = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): __snake_case : str = lines[line_index] __snake_case : List[Any] = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 __snake_case : Tuple = {'''none''': objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. __snake_case : List[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __snake_case : Any = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __snake_case : Optional[Any] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): __snake_case : str = lines[line_index] __snake_case : str = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 __snake_case : List[Any] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def __UpperCAmelCase ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] ) -> Optional[int]: '''simple docstring''' def find_duplicates(UpperCAmelCase_ : Union[str, Any] ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __snake_case : str = [] for key in import_dict_objects.keys(): __snake_case : Any = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}" ) __snake_case : List[Any] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __snake_case : Tuple = '''base imports''' if key == '''none''' else F"{key} backend" errors.append(F"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F" {a} in _import_structure but not in TYPE_HINT." ) return errors def __UpperCAmelCase ( ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: __snake_case : str = os.path.join(A_ , '__init__.py' ) __snake_case : Optional[int] = parse_init(A_ ) if objects is not None: __snake_case : Optional[int] = analyze_results(*A_ ) if len(A_ ) > 0: __snake_case : Dict = F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append('\n'.join(A_ ) ) if len(A_ ) > 0: raise ValueError('\n\n'.join(A_ ) ) def __UpperCAmelCase ( ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[Any] = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob('*.py' ) ) ) == 0: continue __snake_case : Any = str((Path(A_ ) / folder).relative_to(A_ ) ) __snake_case : Optional[int] = short_path.replace(os.path.sep , '.' ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue __snake_case : Any = str((Path(A_ ) / fname).relative_to(A_ ) ) __snake_case : str = short_path.replace('.py' , '' ).replace(os.path.sep , '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(A_ ) return submodules _a : str= [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def __UpperCAmelCase ( ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = importlib.util.spec_from_file_location( 'transformers' , os.path.join(A_ , '__init__.py' ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) __snake_case : Any = spec.loader.load_module() __snake_case : List[str] = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: __snake_case : List[str] = '''\n'''.join(F"- {module}" for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F"{list_of_modules}\n" 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
172
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __UpperCamelCase : int = logging.getLogger(__name__) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): # save results if os.path.exists(A_ ): if os.path.exists(os.path.join(A_ , '''config.json''' ) ) and os.path.isfile( os.path.join(A_ , '''config.json''' ) ): os.remove(os.path.join(A_ , '''config.json''' ) ) if os.path.exists(os.path.join(A_ , '''pytorch_model.bin''' ) ) and os.path.isfile( os.path.join(A_ , '''pytorch_model.bin''' ) ): os.remove(os.path.join(A_ , '''pytorch_model.bin''' ) ) else: os.makedirs(A_ ) model.save_pretrained(A_ ) def __SCREAMING_SNAKE_CASE ( A_ , A_=False ): lowerCAmelCase__ : Optional[Any] = 2 if unlogit: lowerCAmelCase__ : Union[str, Any] = torch.pow(A_ , A_ ) lowerCAmelCase__ : Optional[Any] = p * torch.log(A_ ) lowerCAmelCase__ : List[Any] = 0 return -plogp.sum(dim=-1 ) def __SCREAMING_SNAKE_CASE ( A_ ): logger.info('''lv, h >\t''' + '''\t'''.join(f'{x + 1}' for x in range(len(A_ ) ) ) ) for row in range(len(A_ ) ): if tensor.dtype != torch.long: logger.info(f'layer {row + 1}:\t' + '''\t'''.join(f'{x:.5f}' for x in tensor[row].cpu().data ) ) else: logger.info(f'layer {row + 1}:\t' + '''\t'''.join(f'{x:d}' for x in tensor[row].cpu().data ) ) def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_=True , A_=True , A_=None , A_=False ): lowerCAmelCase__ ,lowerCAmelCase__ : List[Any] = model.config.num_hidden_layers, model.config.num_attention_heads lowerCAmelCase__ : Dict = torch.zeros(A_ , A_ ).to(args.device ) lowerCAmelCase__ : int = torch.zeros(A_ , A_ ).to(args.device ) if head_mask is None: lowerCAmelCase__ : Union[str, Any] = torch.ones(A_ , A_ ).to(args.device ) head_mask.requires_grad_(requires_grad=A_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: lowerCAmelCase__ : Union[str, Any] = None lowerCAmelCase__ : Optional[int] = 0.0 lowerCAmelCase__ : Optional[int] = 0.0 for step, inputs in enumerate(tqdm(A_ , desc='''Iteration''' , disable=args.local_rank not in [-1, 0] ) ): lowerCAmelCase__ : Any = tuple(t.to(args.device ) for t in inputs ) ((lowerCAmelCase__) ,) : List[Any] = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) lowerCAmelCase__ : Any = model(A_ , labels=A_ , head_mask=A_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Dict = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(A_ ): lowerCAmelCase__ : Dict = entropy(attn.detach() , A_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(A_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: lowerCAmelCase__ : Any = 2 lowerCAmelCase__ : Dict = torch.pow(torch.pow(A_ , A_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-2_0 if not args.dont_normalize_global_importance: lowerCAmelCase__ : List[Any] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('''Attention entropies''' ) print_ad_tensor(A_ ) if compute_importance: logger.info('''Head importance scores''' ) print_ad_tensor(A_ ) logger.info('''Head ranked by importance scores''' ) lowerCAmelCase__ : str = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) lowerCAmelCase__ : Optional[int] = torch.arange( head_importance.numel() , device=args.device ) lowerCAmelCase__ : int = head_ranks.view_as(A_ ) print_ad_tensor(A_ ) return attn_entropy, head_importance, total_loss def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : List[str] = compute_heads_importance(A_ , A_ , A_ , compute_entropy=A_ ) lowerCAmelCase__ : Union[str, Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('''Pruning: original score: %f, threshold: %f''' , A_ , original_score * args.masking_threshold ) lowerCAmelCase__ : Union[str, Any] = torch.ones_like(A_ ) lowerCAmelCase__ : List[str] = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) lowerCAmelCase__ : int = original_score while current_score >= original_score * args.masking_threshold: lowerCAmelCase__ : Union[str, Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads lowerCAmelCase__ : str = float('''Inf''' ) lowerCAmelCase__ : List[Any] = head_importance.view(-1 ).sort()[1] if len(A_ ) <= num_to_mask: print('''BREAK BY num_to_mask''' ) break # mask heads lowerCAmelCase__ : List[Any] = current_heads_to_mask[:num_to_mask] logger.info('''Heads to mask: %s''' , str(current_heads_to_mask.tolist() ) ) lowerCAmelCase__ : int = new_head_mask.view(-1 ) lowerCAmelCase__ : Optional[int] = 0.0 lowerCAmelCase__ : Union[str, Any] = new_head_mask.view_as(A_ ) lowerCAmelCase__ : Tuple = new_head_mask.clone().detach() print_ad_tensor(A_ ) # Compute metric and head importance again lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : List[Any] = compute_heads_importance( A_ , A_ , A_ , compute_entropy=A_ , head_mask=A_ ) lowerCAmelCase__ : Tuple = 1 / loss logger.info( '''Masking: current score: %f, remaining heads %d (%.1f percents)''' , A_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_00 , ) logger.info('''Final head mask''' ) print_ad_tensor(A_ ) np.save(os.path.join(args.output_dir , '''head_mask.npy''' ) , head_mask.detach().cpu().numpy() ) return head_mask def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ ): lowerCAmelCase__ : Optional[Any] = datetime.now() lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[Any] = compute_heads_importance( A_ , A_ , A_ , compute_entropy=A_ , compute_importance=A_ , head_mask=A_ ) lowerCAmelCase__ : Optional[Any] = 1 / loss lowerCAmelCase__ : Tuple = datetime.now() - before_time lowerCAmelCase__ : int = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ : List[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(A_ ) ) } for k, v in heads_to_prune.items(): if isinstance(A_ , A_ ): lowerCAmelCase__ : int = [ v, ] assert sum(len(A_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(A_ ) lowerCAmelCase__ : List[Any] = sum(p.numel() for p in model.parameters() ) lowerCAmelCase__ : Any = datetime.now() lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : int = compute_heads_importance( A_ , A_ , A_ , compute_entropy=A_ , compute_importance=A_ , head_mask=A_ , actually_pruned=A_ , ) lowerCAmelCase__ : int = 1 / loss lowerCAmelCase__ : Dict = datetime.now() - before_time logger.info( '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)''' , A_ , A_ , pruned_num_params / original_num_params * 1_00 , ) logger.info('''Pruning: score with masking: %f score with pruning: %f''' , A_ , A_ ) logger.info('''Pruning: speed ratio (original timing / new timing): %f percents''' , original_time / new_time * 1_00 ) save_model(A_ , args.output_dir ) def __SCREAMING_SNAKE_CASE ( ): lowerCAmelCase__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--data_dir''' , default=A_ , type=A_ , required=A_ , help='''The input data dir. Should contain the .tsv files (or other data files) for the task.''' , ) 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( '''--output_dir''' , default=A_ , type=A_ , required=A_ , help='''The output directory where the model predictions and checkpoints will be written.''' , ) # Other parameters parser.add_argument( '''--config_name''' , default='''''' , type=A_ , help='''Pretrained config name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--tokenizer_name''' , default='''''' , type=A_ , help='''Pretrained tokenizer name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--cache_dir''' , default=A_ , type=A_ , help='''Where do you want to store the pre-trained models downloaded from s3''' , ) parser.add_argument( '''--data_subset''' , type=A_ , default=-1 , help='''If > 0: limit the data to a subset of data_subset instances.''' ) parser.add_argument( '''--overwrite_output_dir''' , action='''store_true''' , help='''Whether to overwrite data in output directory''' ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) parser.add_argument( '''--dont_normalize_importance_by_layer''' , action='''store_true''' , help='''Don\'t normalize importance score by layers''' ) parser.add_argument( '''--dont_normalize_global_importance''' , action='''store_true''' , help='''Don\'t normalize all importance scores between 0 and 1''' , ) parser.add_argument( '''--try_masking''' , action='''store_true''' , help='''Whether to try to mask head until a threshold of accuracy.''' ) parser.add_argument( '''--masking_threshold''' , default=0.9 , type=A_ , help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).''' , ) parser.add_argument( '''--masking_amount''' , default=0.1 , type=A_ , help='''Amount to heads to masking at each masking step.''' ) parser.add_argument('''--metric_name''' , default='''acc''' , type=A_ , help='''Metric to use for head masking.''' ) parser.add_argument( '''--max_seq_length''' , default=1_28 , type=A_ , help=( '''The maximum total input sequence length after WordPiece tokenization. \n''' '''Sequences longer than this will be truncated, sequences shorter padded.''' ) , ) parser.add_argument('''--batch_size''' , default=1 , type=A_ , help='''Batch size.''' ) parser.add_argument('''--seed''' , type=A_ , default=42 ) parser.add_argument('''--local_rank''' , type=A_ , default=-1 , help='''local_rank for distributed training on gpus''' ) parser.add_argument('''--no_cuda''' , action='''store_true''' , help='''Whether not to use CUDA when available''' ) parser.add_argument('''--server_ip''' , type=A_ , default='''''' , help='''Can be used for distant debugging.''' ) parser.add_argument('''--server_port''' , type=A_ , default='''''' , help='''Can be used for distant debugging.''' ) lowerCAmelCase__ : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('''Waiting for debugger attach''' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=A_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: lowerCAmelCase__ : Union[str, Any] = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''' ) lowerCAmelCase__ : str = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) lowerCAmelCase__ : Dict = torch.device('''cuda''' , args.local_rank ) lowerCAmelCase__ : Union[str, Any] = 1 torch.distributed.init_process_group(backend='''nccl''' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) lowerCAmelCase__ : List[str] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: lowerCAmelCase__ : Dict = nn.parallel.DistributedDataParallel( A_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=A_ ) elif args.n_gpu > 1: lowerCAmelCase__ : List[Any] = nn.DataParallel(A_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=A_ ) torch.save(A_ , os.path.join(args.output_dir , '''run_args.bin''' ) ) logger.info('''Training/evaluation parameters %s''' , A_ ) # Prepare dataset lowerCAmelCase__ : str = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) lowerCAmelCase__ : Union[str, Any] = (torch.from_numpy(A_ ),) lowerCAmelCase__ : Tuple = TensorDataset(*A_ ) lowerCAmelCase__ : Optional[int] = RandomSampler(A_ ) lowerCAmelCase__ : Dict = DataLoader(A_ , sampler=A_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(A_ , A_ , A_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: lowerCAmelCase__ : Tuple = mask_heads(A_ , A_ , A_ ) prune_heads(A_ , A_ , A_ , A_ ) if __name__ == "__main__": main()
106
0
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Tuple = None __lowerCamelCase : int = BloomTokenizerFast __lowerCamelCase : Union[str, Any] = BloomTokenizerFast __lowerCamelCase : Any = True __lowerCamelCase : List[str] = False __lowerCamelCase : str = "tokenizer_file" __lowerCamelCase : Any = {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"} def _lowerCAmelCase ( self ): super().setUp() A : List[Any] = BloomTokenizerFast.from_pretrained("""bigscience/tokenizer""" ) tokenizer.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : List[Any] = self.get_rust_tokenizer() A : Tuple = ["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""] A : List[Any] = [[2175, 2_3714, 7_3173, 14_4252, 2], [77, 13_2619, 3478, 368, 10_9586, 3_5433, 2]] A : Dict = tokenizer.batch_encode_plus(lowerCamelCase__ )["""input_ids"""] self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) A : Tuple = tokenizer.batch_decode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__=6 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): A : int = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__, **lowerCamelCase__ ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input A : Tuple = """This is a simple input""" A : Optional[Any] = ["""This is a simple input 1""", """This is a simple input 2"""] A : Optional[Any] = ("""This is a simple input""", """This is a pair""") A : Union[str, Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests try: tokenizer_r.encode(lowerCamelCase__, max_length=lowerCamelCase__ ) tokenizer_r.encode_plus(lowerCamelCase__, max_length=lowerCamelCase__ ) tokenizer_r.batch_encode_plus(lowerCamelCase__, max_length=lowerCamelCase__ ) tokenizer_r.encode(lowerCamelCase__, max_length=lowerCamelCase__ ) tokenizer_r.batch_encode_plus(lowerCamelCase__, max_length=lowerCamelCase__ ) except ValueError: self.fail("""Bloom Tokenizer should be able to deal with padding""" ) A : int = None # Hotfixing padding = None self.assertRaises(lowerCamelCase__, tokenizer_r.encode, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Simple input self.assertRaises(lowerCamelCase__, tokenizer_r.encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Simple input self.assertRaises( lowerCamelCase__, tokenizer_r.batch_encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""", ) # Pair input self.assertRaises(lowerCamelCase__, tokenizer_r.encode, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Pair input self.assertRaises(lowerCamelCase__, tokenizer_r.encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""" ) # Pair input self.assertRaises( lowerCamelCase__, tokenizer_r.batch_encode_plus, lowerCamelCase__, max_length=lowerCamelCase__, padding="""max_length""", ) def _lowerCAmelCase ( self ): A : List[str] = self.get_rust_tokenizer() A : int = load_dataset("""xnli""", """all_languages""", split="""test""", streaming=lowerCamelCase__ ) A : Dict = next(iter(lowerCamelCase__ ) )["""premise"""] # pick up one data A : Any = list(sample_data.values() ) A : Tuple = list(map(tokenizer.encode, lowerCamelCase__ ) ) A : Any = [tokenizer.decode(lowerCamelCase__, clean_up_tokenization_spaces=lowerCamelCase__ ) for x in output_tokens] self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ), 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ), 1 )
115
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_:Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:Union[str, Any] = """https://openaipublic.azureedge.net/jukebox/models/""" SCREAMING_SNAKE_CASE_:Optional[int] = { """jukebox-1b-lyrics""": [ """5b/vqvae.pth.tar""", """5b/prior_level_0.pth.tar""", """5b/prior_level_1.pth.tar""", """1b_lyrics/prior_level_2.pth.tar""", ], """jukebox-5b-lyrics""": [ """5b/vqvae.pth.tar""", """5b/prior_level_0.pth.tar""", """5b/prior_level_1.pth.tar""", """5b_lyrics/prior_level_2.pth.tar""", ], } def __UpperCamelCase ( _lowerCAmelCase ) -> Dict: """simple docstring""" if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: A : Optional[int] = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: A : Any = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: A : str = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: A : Optional[Any] = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: A : List[str] = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: A : Tuple = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: A : List[str] = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: A : Optional[int] = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Tuple: """simple docstring""" A : List[str] = {} import re A : Any = re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) A : str = re.compile( R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) A : Union[str, Any] = re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) A : List[Any] = re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) A : Optional[Any] = re.compile( R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) A : List[str] = re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) A : Optional[Any] = re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) A : Tuple = re.compile( R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) A : List[Any] = re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_lowerCAmelCase ): A : Optional[Any] = re_encoder_block_conv_in.match(_lowerCAmelCase ) A : Tuple = regex_match.groups() A : str = int(groups[2] ) * 2 + int(groups[3] ) A : int = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' A : Any = re_encoder_block_conv_in.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_encoder_block_resnet.fullmatch(_lowerCAmelCase ): A : Optional[int] = re_encoder_block_resnet.match(_lowerCAmelCase ) A : str = regex_match.groups() A : Optional[int] = int(groups[2] ) * 2 + int(groups[3] ) A : Any = {"""1""": 1, """3""": 2}[groups[-2]] A : int = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' A : List[str] = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' A : str = prefix + resnet_block A : str = re_encoder_block_resnet.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_encoder_block_proj_out.fullmatch(_lowerCAmelCase ): A : List[str] = re_encoder_block_proj_out.match(_lowerCAmelCase ) A : List[Any] = regex_match.groups() A : List[Any] = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' A : Optional[int] = re_encoder_block_proj_out.sub(_lowerCAmelCase , _lowerCAmelCase ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_lowerCAmelCase ): A : Union[str, Any] = re_decoder_block_conv_out.match(_lowerCAmelCase ) A : Dict = regex_match.groups() A : Union[str, Any] = int(groups[2] ) * 2 + int(groups[3] ) - 2 A : Optional[int] = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' A : int = re_decoder_block_conv_out.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_decoder_block_resnet.fullmatch(_lowerCAmelCase ): A : Optional[int] = re_decoder_block_resnet.match(_lowerCAmelCase ) A : List[Any] = regex_match.groups() A : List[str] = int(groups[2] ) * 2 + int(groups[3] ) - 2 A : str = {"""1""": 1, """3""": 2}[groups[-2]] A : Optional[int] = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' A : Union[str, Any] = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' A : Tuple = prefix + resnet_block A : Tuple = re_decoder_block_resnet.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_decoder_block_proj_in.fullmatch(_lowerCAmelCase ): A : Optional[Any] = re_decoder_block_proj_in.match(_lowerCAmelCase ) A : Any = regex_match.groups() A : Optional[Any] = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' A : Dict = re_decoder_block_proj_in.sub(_lowerCAmelCase , _lowerCAmelCase ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_lowerCAmelCase ): A : Optional[int] = re_prior_cond_conv_out.match(_lowerCAmelCase ) A : List[Any] = regex_match.groups() A : List[Any] = int(groups[1] ) * 2 + int(groups[2] ) - 2 A : Tuple = f'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' A : List[str] = re_prior_cond_conv_out.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_prior_cond_resnet.fullmatch(_lowerCAmelCase ): A : Any = re_prior_cond_resnet.match(_lowerCAmelCase ) A : Any = regex_match.groups() A : Tuple = int(groups[1] ) * 2 + int(groups[2] ) - 2 A : Optional[Any] = {"""1""": 1, """3""": 2}[groups[-2]] A : Tuple = f'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' A : List[str] = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' A : Dict = prefix + resnet_block A : Union[str, Any] = re_prior_cond_resnet.sub(_lowerCAmelCase , _lowerCAmelCase ) elif re_prior_cond_proj_in.fullmatch(_lowerCAmelCase ): A : List[Any] = re_prior_cond_proj_in.match(_lowerCAmelCase ) A : Optional[int] = regex_match.groups() A : Tuple = f'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' A : Optional[int] = re_prior_cond_proj_in.sub(_lowerCAmelCase , _lowerCAmelCase ) # keep original key else: A : str = original_key A : List[str] = replace_key(_lowerCAmelCase ) if f'''{key_prefix}.{key}''' not in model_state_dict or key is None: print(f'''failed converting {original_key} to {key}, does not match''' ) # handle missmatched shape elif value.shape != model_state_dict[f'''{key_prefix}.{key}'''].shape: A : str = model_state_dict[f'''{key_prefix}.{key}'''] print(f'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) A : Union[str, Any] = original_key A : Union[str, Any] = original_key A : List[str] = value return new_dict @torch.no_grad() def __UpperCamelCase ( _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Tuple: """simple docstring""" for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): A : Optional[Any] = requests.get(f'''{PREFIX}{file}''' , allow_redirects=_lowerCAmelCase ) os.makedirs(f'''{pytorch_dump_folder_path}/''' , exist_ok=_lowerCAmelCase ) open(f'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , """wb""" ).write(r.content ) A : Optional[int] = MODEL_MAPPING[model_name.split("""/""" )[-1]] A : List[Any] = JukeboxConfig.from_pretrained(_lowerCAmelCase ) A : Dict = JukeboxModel(_lowerCAmelCase ) A : str = [] A : Optional[int] = {} for i, dict_name in enumerate(_lowerCAmelCase ): A : str = torch.load(f'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )["""model"""] A : Optional[int] = {} for k in old_dic.keys(): if k.endswith(""".b""" ): A : Dict = old_dic[k] elif k.endswith(""".w""" ): A : Optional[Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: A : Union[str, Any] = old_dic[k] else: A : Optional[int] = old_dic[k] A : List[str] = """vqvae""" if i == 0 else f'''priors.{3 - i}''' A : List[Any] = fix_jukebox_keys(_lowerCAmelCase , model.state_dict() , _lowerCAmelCase , _lowerCAmelCase ) weight_dict.append(_lowerCAmelCase ) A : List[Any] = weight_dict.pop(0 ) model.vqvae.load_state_dict(_lowerCAmelCase ) for i in range(len(_lowerCAmelCase ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) with open(f'''{pytorch_dump_folder_path}/mapping.json''' , """w""" ) as txtfile: json.dump(_lowerCAmelCase , _lowerCAmelCase ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_lowerCAmelCase ) return weight_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_:List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""jukebox-5b-lyrics""", type=str, help="""Name of the model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""jukebox-5b-lyrics-converted""", type=str, help="""Path to the output PyTorch model directory.""", ) SCREAMING_SNAKE_CASE_:int = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
115
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def snake_case_ ( ): """simple docstring""" assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
93
"""simple docstring""" import datasets from .evaluate import evaluate A: Optional[Any] = "\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n" A: Optional[int] = "\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n" A: int = "\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair as given in the references (see below)\n - 'prediction_text': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair (see above),\n - 'answers': a Dict in the CUAD dataset format\n {\n 'text': list of possible texts for the answer, as a list of strings\n 'answer_start': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n 'exact_match': Exact match (the normalized answer exactly match the gold answer)\n 'f1': The F-score of predicted tokens versus the gold answer\n 'aupr': Area Under the Precision-Recall curve\n 'prec_at_80_recall': Precision at 80% recall\n 'prec_at_90_recall': Precision at 90% recall\nExamples:\n >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n >>> cuad_metric = datasets.load_metric(\"cuad\")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' UpperCAmelCase : int = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} UpperCAmelCase : Tuple = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] UpperCAmelCase : Optional[Any] = evaluate(dataset=_SCREAMING_SNAKE_CASE , predictions=_SCREAMING_SNAKE_CASE ) return score
109
0
"""simple docstring""" import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __lowercase = logging.get_logger(__name__) def lowerCAmelCase (__UpperCamelCase : Tuple ): """simple docstring""" __UpperCamelCase =torch.load(__a , map_location='''cpu''' ) if "model" in sd.keys(): __UpperCamelCase =torch.load(__a , map_location='''cpu''' )['model'] # pop unnecessary weights __UpperCamelCase =[ 'decoder.version', 'decoder.output_projection.weight', ] for key in keys_to_delete: if key in sd: sd.pop(__a ) __UpperCamelCase ={ 'decoder.project_in_dim.weight': 'decoder.project_in.weight', 'decoder.project_out_dim.weight': 'decoder.project_out.weight', 'decoder.layer_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.layer_norm.bias': 'decoder.final_layer_norm.bias', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: __UpperCamelCase =sd.pop(__a ) __UpperCamelCase =list(sd.keys() ) for key in keys: if ".qkv_proj." in key: __UpperCamelCase =sd[key] # We split QKV in separate Q,K,V __UpperCamelCase =key.replace('''.qkv_proj.''' , '''.q_proj.''' ) __UpperCamelCase =key.replace('''.qkv_proj.''' , '''.k_proj.''' ) __UpperCamelCase =key.replace('''.qkv_proj.''' , '''.v_proj.''' ) __UpperCamelCase =value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 __UpperCamelCase =torch.split(__a , depth // 3 , dim=0 ) __UpperCamelCase =q __UpperCamelCase =k __UpperCamelCase =v del sd[key] return sd @torch.no_grad() def lowerCAmelCase (__UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : Dict=None ): """simple docstring""" __UpperCamelCase =load_checkpoint(__a ) if config is not None: __UpperCamelCase =OPTConfig.from_pretrained(__a ) else: __UpperCamelCase =OPTConfig() __UpperCamelCase =OPTModel(__a ).half().eval() model.load_state_dict(__a ) # Check results Path(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) if __name__ == "__main__": __lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--fairseq_path''', type=str, help=( '''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:''' ''' https://huggingface.co/models?other=opt_metasq''' ), ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''') __lowercase = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
371
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __lowercase = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
85
0
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase_ : '''simple docstring''' def __init__( self , __lowercase , __lowercase=13 , __lowercase=30 , __lowercase=2 , __lowercase=3 , __lowercase=True , __lowercase=True , __lowercase=32 , __lowercase=5 , __lowercase=4 , __lowercase=37 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=10 , __lowercase=0.02 , __lowercase=None , ) -> List[str]: __UpperCamelCase :str = parent __UpperCamelCase :Optional[int] = batch_size __UpperCamelCase :List[str] = image_size __UpperCamelCase :str = patch_size __UpperCamelCase :Union[str, Any] = num_channels __UpperCamelCase :Dict = is_training __UpperCamelCase :str = use_labels __UpperCamelCase :Dict = hidden_size __UpperCamelCase :List[Any] = num_hidden_layers __UpperCamelCase :int = num_attention_heads __UpperCamelCase :Tuple = intermediate_size __UpperCamelCase :Union[str, Any] = hidden_act __UpperCamelCase :List[Any] = hidden_dropout_prob __UpperCamelCase :Optional[Any] = attention_probs_dropout_prob __UpperCamelCase :Any = type_sequence_label_size __UpperCamelCase :Optional[Any] = initializer_range __UpperCamelCase :str = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase :Union[str, Any] = (image_size // patch_size) ** 2 __UpperCamelCase :List[Any] = num_patches + 1 def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __UpperCamelCase :Optional[Any] = None if self.use_labels: __UpperCamelCase :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self) -> List[str]: return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> Union[str, Any]: __UpperCamelCase :int = ViTMSNModel(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __UpperCamelCase :Union[str, Any] = model(_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> Dict: __UpperCamelCase :List[Any] = self.type_sequence_label_size __UpperCamelCase :Any = ViTMSNForImageClassification(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __UpperCamelCase :Union[str, Any] = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''') print('''Labels: {labels}''') self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __UpperCamelCase :List[str] = 1 __UpperCamelCase :int = ViTMSNForImageClassification(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __UpperCamelCase :Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __UpperCamelCase :int = model(_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() __UpperCamelCase :Any = config_and_inputs __UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Optional[int] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () a__ : str = ( {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification} if is_torch_available() else {} ) a__ : str = False a__ : str = False a__ : int = False a__ : List[str] = False def UpperCamelCase__ ( self) -> int: __UpperCamelCase :Optional[int] = ViTMSNModelTester(self) __UpperCamelCase :Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37) def UpperCamelCase__ ( self) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''') def UpperCamelCase__ ( self) -> List[Any]: pass def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :Tuple = model_class(_SCREAMING_SNAKE_CASE) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) __UpperCamelCase :Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear)) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :Optional[Any] = model_class(_SCREAMING_SNAKE_CASE) __UpperCamelCase :List[str] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase :Dict = [*signature.parameters.keys()] __UpperCamelCase :List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE) def UpperCamelCase__ ( self) -> int: __UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE) def UpperCamelCase__ ( self) -> str: __UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE) @slow def UpperCamelCase__ ( self) -> Dict: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase :Optional[Any] = ViTMSNModel.from_pretrained(_SCREAMING_SNAKE_CASE) self.assertIsNotNone(_SCREAMING_SNAKE_CASE) def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self) -> Tuple: return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''') if is_vision_available() else None @slow def UpperCamelCase__ ( self) -> Union[str, Any]: torch.manual_seed(2) __UpperCamelCase :List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''').to(_SCREAMING_SNAKE_CASE) __UpperCamelCase :Tuple = self.default_image_processor __UpperCamelCase :List[Any] = prepare_img() __UpperCamelCase :Optional[int] = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='''pt''').to(_SCREAMING_SNAKE_CASE) # forward pass with torch.no_grad(): __UpperCamelCase :Tuple = model(**_SCREAMING_SNAKE_CASE) # verify the logits __UpperCamelCase :int = torch.Size((1, 1_000)) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE) __UpperCamelCase :Optional[int] = torch.tensor([-0.08_03, -0.44_54, -0.23_75]).to(_SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4))
43
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=2 ): from .. import __version__ A_ : Union[str, Any] = take_from A_ : Optional[Any] = () if not isinstance(args[0] , SCREAMING_SNAKE_CASE ): A_ : List[str] = (args,) for attribute, version_name, message in args: if version.parse(version.parse(SCREAMING_SNAKE_CASE ).base_version ) >= version.parse(SCREAMING_SNAKE_CASE ): raise ValueError( f'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' f''' version {__version__} is >= {version_name}''' ) A_ : List[Any] = None if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(SCREAMING_SNAKE_CASE ),) A_ : Optional[Any] = f'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): values += (getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ),) A_ : int = f'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: A_ : List[Any] = f'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: A_ : Union[str, Any] = warning + ''' ''' if standard_warn else '''''' warnings.warn(warning + message , SCREAMING_SNAKE_CASE , stacklevel=SCREAMING_SNAKE_CASE ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) > 0: A_ : Dict = inspect.getouterframes(inspect.currentframe() )[1] A_ : Optional[int] = call_frame.filename A_ : Optional[int] = call_frame.lineno A_ : str = call_frame.function A_ , A_ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(SCREAMING_SNAKE_CASE ) == 0: return elif len(SCREAMING_SNAKE_CASE ) == 1: return values[0] return values
186
0
from math import factorial __A ={str(d): factorial(d) for d in range(1_0)} def lowerCamelCase_ ( lowerCamelCase__ ): return sum(DIGIT_FACTORIAL[d] for d in str(a__ ) ) def lowerCamelCase_ ( ): lowerCamelCase_ = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , a__ ) if sum_of_digit_factorial(a__ ) == i ) if __name__ == "__main__": print(F"""{solution() = }""")
368
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter __A =True except ImportError: __A =False __A =logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCamelCase_ ( lowerCamelCase__ ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class _SCREAMING_SNAKE_CASE ( snake_case_ ): @staticmethod def SCREAMING_SNAKE_CASE_( lowercase ) -> int: lowerCamelCase_ = parser.add_parser("add-new-model" ) add_new_model_parser.add_argument("--testing" , action="store_true" , help="If in testing mode." ) add_new_model_parser.add_argument("--testing_file" , type=lowercase , help="Configuration file on which to run." ) add_new_model_parser.add_argument( "--path" , type=lowercase , help="Path to cookiecutter. Should only be used for testing purposes." ) add_new_model_parser.set_defaults(func=lowercase ) def __init__( self , lowercase , lowercase , lowercase=None , *lowercase ) -> List[str]: lowerCamelCase_ = testing lowerCamelCase_ = testing_file lowerCamelCase_ = path def SCREAMING_SNAKE_CASE_( self ) -> str: warnings.warn( "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. " "It is not actively maintained anymore, so might give a result that won't pass all tests and quality " "checks, you should use `transformers-cli add-new-model-like` instead." ) if not _has_cookiecutter: raise ImportError( "Model creation dependencies are required to use the `add_new_model` command. Install them by running " "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n" ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory lowerCamelCase_ = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]] if len(lowercase ) > 0: raise ValueError( "Several directories starting with `cookiecutter-template-` in current working directory. " "Please clean your directory by removing all folders starting with `cookiecutter-template-` or " "change your working directory." ) lowerCamelCase_ = ( Path(lowercase ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) lowerCamelCase_ = path_to_transformer_root / "templates" / "adding_a_new_model" # Execute cookiecutter if not self._testing: cookiecutter(str(lowercase ) ) else: with open(self._testing_file , "r" ) as configuration_file: lowerCamelCase_ = json.load(lowercase ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=lowercase , extra_context=lowercase , ) lowerCamelCase_ = [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0] # Retrieve configuration with open(directory + "/configuration.json" , "r" ) as configuration_file: lowerCamelCase_ = json.load(lowercase ) lowerCamelCase_ = configuration["lowercase_modelname"] lowerCamelCase_ = configuration["generate_tensorflow_pytorch_and_flax"] os.remove(f'{directory}/configuration.json' ) lowerCamelCase_ = "PyTorch" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ = "TensorFlow" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ = "Flax" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ = f'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(lowercase , exist_ok=lowercase ) os.makedirs(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}' , exist_ok=lowercase ) # Tests require submodules as they have parent imports with open(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' , "w" ): pass shutil.move( f'{directory}/__init__.py' , f'{model_dir}/__init__.py' , ) shutil.move( f'{directory}/configuration_{lowercase_model_name}.py' , f'{model_dir}/configuration_{lowercase_model_name}.py' , ) def remove_copy_lines(lowercase ): with open(lowercase , "r" ) as f: lowerCamelCase_ = f.readlines() with open(lowercase , "w" ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(lowercase ) if output_pytorch: if not self._testing: remove_copy_lines(f'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_{lowercase_model_name}.py' , f'{model_dir}/modeling_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_tf_{lowercase_model_name}.py' , f'{model_dir}/modeling_tf_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_tf_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_flax_{lowercase_model_name}.py' , f'{model_dir}/modeling_flax_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_flax_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/{lowercase_model_name}.md' , f'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' , ) shutil.move( f'{directory}/tokenization_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/tokenization_fast_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}_fast.py' , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(lowercase , lowercase , lowercase ): # Create temp file lowerCamelCase_ , lowerCamelCase_ = mkstemp() lowerCamelCase_ = False with fdopen(lowercase , "w" ) as new_file: with open(lowercase ) as old_file: for line in old_file: new_file.write(lowercase ) if line_to_copy_below in line: lowerCamelCase_ = True for line_to_copy in lines_to_copy: new_file.write(lowercase ) if not line_found: raise ValueError(f'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(lowercase , lowercase ) # Remove original file remove(lowercase ) # Move new file move(lowercase , lowercase ) def skip_units(lowercase ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(lowercase ): with open(lowercase ) as datafile: lowerCamelCase_ = [] lowerCamelCase_ = False lowerCamelCase_ = False for line in datafile: if "# To replace in: " in line and "##" not in line: lowerCamelCase_ = line.split("\"" )[1] lowerCamelCase_ = skip_units(lowercase ) elif "# Below: " in line and "##" not in line: lowerCamelCase_ = line.split("\"" )[1] lowerCamelCase_ = skip_units(lowercase ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(lowercase , lowercase , lowercase ) lowerCamelCase_ = [] elif "# Replace with" in line and "##" not in line: lowerCamelCase_ = [] elif "##" not in line: lines_to_copy.append(lowercase ) remove(lowercase ) replace_in_files(f'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(lowercase )
47
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_A ) class _UpperCAmelCase ( _A ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization SCREAMING_SNAKE_CASE_ : str = field(default="question-answering-extractive" , metadata={"include_in_asdict_even_if_is_default": True} ) SCREAMING_SNAKE_CASE_ : ClassVar[Features] = Features({"question": Value("string" ), "context": Value("string" )} ) SCREAMING_SNAKE_CASE_ : ClassVar[Features] = Features( { "answers": Sequence( { "text": Value("string" ), "answer_start": Value("int32" ), } ) } ) SCREAMING_SNAKE_CASE_ : str = "question" SCREAMING_SNAKE_CASE_ : str = "context" SCREAMING_SNAKE_CASE_ : str = "answers" @property def A ( self : Any ) -> Dict[str, str]: return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
33
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
0
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class __A( __UpperCamelCase ): snake_case_ = 42 snake_case_ = None def __lowerCAmelCase ( a__ , a__=0.999 , a__="cosine" , ) -> Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(a__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a__ ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) __a = [] for i in range(lowercase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowercase__ ) / alpha_bar_fn(lowercase__ ) , lowercase__ ) ) return torch.tensor(lowercase__ , dtype=torch.floataa ) class __A( __UpperCamelCase , __UpperCamelCase ): @register_to_config def __init__( self , _snake_case = 1_000 , _snake_case = "fixed_small_log" , _snake_case = True , _snake_case = 1.0 , _snake_case = "epsilon" , _snake_case = "squaredcos_cap_v2" , ) -> List[Any]: '''simple docstring''' if beta_schedule != "squaredcos_cap_v2": raise ValueError('''UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'''' ) __a = betas_for_alpha_bar(_snake_case ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) __a = torch.tensor(1.0 ) # standard deviation of the initial noise distribution __a = 1.0 # setable values __a = None __a = torch.from_numpy(np.arange(0 , _snake_case )[::-1].copy() ) __a = variance_type def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None ) -> Union[str, Any]: '''simple docstring''' return sample def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None ) -> Any: '''simple docstring''' __a = num_inference_steps __a = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) __a = (np.arange(0 , _snake_case ) * step_ratio).round()[::-1].copy().astype(np.intaa ) __a = torch.from_numpy(_snake_case ).to(_snake_case ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case=None , _snake_case=None , _snake_case=None ) -> str: '''simple docstring''' if prev_timestep is None: __a = t - 1 __a = self.alphas_cumprod[t] __a = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __a = 1 - alpha_prod_t __a = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __a = self.betas[t] else: __a = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample __a = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: __a = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": __a = torch.log(torch.clamp(_snake_case , min=1E-20 ) ) __a = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler __a = variance.log() __a = beta.log() __a = (predicted_variance + 1) / 2 __a = frac * max_log + (1 - frac) * min_log return variance def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case = None , _snake_case=None , _snake_case = True , ) -> List[Any]: '''simple docstring''' __a = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": __a = torch.split(_snake_case , sample.shape[1] , dim=1 ) else: __a = None # 1. compute alphas, betas if prev_timestep is None: __a = t - 1 __a = self.alphas_cumprod[t] __a = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __a = 1 - alpha_prod_t __a = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __a = self.betas[t] __a = self.alphas[t] else: __a = 1 - alpha_prod_t / alpha_prod_t_prev __a = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": __a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": __a = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`""" ''' for the UnCLIPScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: __a = torch.clamp( _snake_case , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __a = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t __a = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __a = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __a = 0 if t > 0: __a = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=_snake_case , device=model_output.device ) __a = self._get_variance( _snake_case , predicted_variance=_snake_case , prev_timestep=_snake_case , ) if self.variance_type == "fixed_small_log": __a = variance elif self.variance_type == "learned_range": __a = (0.5 * variance).exp() else: raise ValueError( F"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`""" ''' for the UnCLIPScheduler.''' ) __a = variance * variance_noise __a = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_snake_case , pred_original_sample=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , ) -> Optional[Any]: '''simple docstring''' __a = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) __a = timesteps.to(original_samples.device ) __a = alphas_cumprod[timesteps] ** 0.5 __a = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): __a = sqrt_alpha_prod.unsqueeze(-1 ) __a = (1 - alphas_cumprod[timesteps]) ** 0.5 __a = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): __a = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) __a = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
356
import os # Precomputes a list of the 100 first triangular numbers A : List[Any] = [int(0.5 * n * (n + 1)) for n in range(1, 1_0_1)] def __lowerCAmelCase ( ) -> Tuple: __a = os.path.dirname(os.path.realpath(a__ ) ) __a = os.path.join(a__ , '''words.txt''' ) __a = '''''' with open(a__ ) as f: __a = f.readline() __a = [word.strip('''"''' ) for word in words.strip('''\r\n''' ).split(''',''' )] __a = [ word for word in [sum(ord(a__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(a__ ) if __name__ == "__main__": print(solution())
33
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self :List[Any] ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase__ : Any =UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model def UpperCAmelCase__ ( self :List[Any] ): """simple docstring""" lowerCamelCase__ : List[Any] =self.dummy_uncond_unet lowerCamelCase__ : int =ScoreSdeVeScheduler() lowerCamelCase__ : Union[str, Any] =ScoreSdeVePipeline(unet=__lowercase , scheduler=__lowercase ) sde_ve.to(__lowercase ) sde_ve.set_progress_bar_config(disable=__lowercase ) lowerCamelCase__ : str =torch.manual_seed(0 ) lowerCamelCase__ : List[str] =sde_ve(num_inference_steps=2 , output_type='numpy' , generator=__lowercase ).images lowerCamelCase__ : Optional[int] =torch.manual_seed(0 ) lowerCamelCase__ : List[Any] =sde_ve(num_inference_steps=2 , output_type='numpy' , generator=__lowercase , return_dict=__lowercase )[ 0 ] lowerCamelCase__ : List[str] =image[0, -3:, -3:, -1] lowerCamelCase__ : Union[str, Any] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase__ : List[Any] =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class A_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self :Dict ): """simple docstring""" lowerCamelCase__ : List[str] ='google/ncsnpp-church-256' lowerCamelCase__ : str =UNetaDModel.from_pretrained(__lowercase ) lowerCamelCase__ : Union[str, Any] =ScoreSdeVeScheduler.from_pretrained(__lowercase ) lowerCamelCase__ : Tuple =ScoreSdeVePipeline(unet=__lowercase , scheduler=__lowercase ) sde_ve.to(__lowercase ) sde_ve.set_progress_bar_config(disable=__lowercase ) lowerCamelCase__ : List[Any] =torch.manual_seed(0 ) lowerCamelCase__ : Any =sde_ve(num_inference_steps=10 , output_type='numpy' , generator=__lowercase ).images lowerCamelCase__ : Optional[int] =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowerCamelCase__ : Tuple =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
126
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __magic_name__( lowerCamelCase=None, lowerCamelCase=None): return field(default_factory=lambda: default, metadata=lowerCamelCase) @dataclass class a__ : """simple docstring""" __UpperCamelCase : str = field( metadata={'help': 'The csv file to plot.'} , ) __UpperCamelCase : bool = field( default=__A , metadata={'help': 'Whether to plot along batch size or sequence length. Defaults to sequence length.'} , ) __UpperCamelCase : bool = field( default=__A , metadata={'help': 'Whether the csv file has time results or memory results. Defaults to memory results.'} , ) __UpperCamelCase : bool = field( default=__A , metadata={'help': 'Disable logarithmic scale when plotting'} , ) __UpperCamelCase : bool = field( default=__A , metadata={ 'help': 'Whether the csv file has training results or inference results. Defaults to inference results.' } , ) __UpperCamelCase : Optional[str] = field( default=__A , metadata={'help': 'Filename under which the plot will be saved. If unused no plot is saved.'} , ) __UpperCamelCase : Optional[List[str]] = list_field( default=__A , metadata={'help': 'List of model names that are used instead of the ones in the csv file.'} ) def __magic_name__( lowerCamelCase): try: int(lowerCamelCase) return True except ValueError: return False def __magic_name__( lowerCamelCase): try: float(lowerCamelCase) return True except ValueError: return False class a__ : """simple docstring""" def __init__(self , __lowercase ): __lowerCAmelCase = args __lowerCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: __lowerCAmelCase = csv.DictReader(__lowercase ) for row in reader: __lowerCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None __lowerCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None __lowerCAmelCase = float(row['''result'''] ) def _snake_case (self ): __lowerCAmelCase , __lowerCAmelCase = plt.subplots() __lowerCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' __lowerCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): __lowerCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) __lowerCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) __lowerCAmelCase = self.result_dict[model_name]['''result'''] ((__lowerCAmelCase) , (__lowerCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) __lowerCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: __lowerCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=__lowercase , ) else: __lowerCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((__lowerCAmelCase) , (__lowerCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) __lowerCAmelCase = np.asarray(__lowercase , __lowercase )[: len(__lowercase )] plt.scatter( __lowercase , __lowercase , label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" ) plt.plot(__lowercase , __lowercase , '''--''' ) title_str += F""" {label_model_name} vs.""" __lowerCAmelCase = title_str[:-4] __lowerCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(__lowercase ) plt.xlabel(__lowercase ) plt.ylabel(__lowercase ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __magic_name__( ): __lowerCAmelCase = HfArgumentParser(lowerCamelCase) __lowerCAmelCase = parser.parse_args_into_dataclasses()[0] __lowerCAmelCase = Plot(args=lowerCamelCase) plot.plot() if __name__ == "__main__": main()
174
0
"""simple docstring""" def lowerCAmelCase (): """simple docstring""" return 1 def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else five_pence(x - 5 ) + two_pence(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else ten_pence(x - 1_0 ) + five_pence(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else twenty_pence(x - 2_0 ) + ten_pence(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else fifty_pence(x - 5_0 ) + twenty_pence(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else one_pound(x - 1_0_0 ) + fifty_pence(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int ): """simple docstring""" return 0 if x < 0 else two_pound(x - 2_0_0 ) + one_pound(__UpperCamelCase ) def lowerCAmelCase (__UpperCamelCase : int = 2_0_0 ): """simple docstring""" return two_pound(__UpperCamelCase ) if __name__ == "__main__": print(solution(int(input().strip())))
85
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Any class _lowercase : """simple docstring""" def __init__( self : int , UpperCamelCase__ : Any ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase =data __UpperCamelCase =None class _lowercase : """simple docstring""" def __init__( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' __UpperCamelCase =None __UpperCamelCase =None def __iter__( self : int ) -> Iterator[Any]: '''simple docstring''' __UpperCamelCase =self.head while self.head: yield node.data __UpperCamelCase =node.next if node == self.head: break def __len__( self : Union[str, Any] ) -> int: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : str ) -> Union[str, Any]: '''simple docstring''' return "->".join(str(UpperCamelCase__ ) for item in iter(self ) ) def UpperCAmelCase_ ( self : List[str] , UpperCamelCase__ : Any ) -> None: '''simple docstring''' self.insert_nth(len(self ) , UpperCamelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCamelCase__ : Any ) -> None: '''simple docstring''' self.insert_nth(0 , UpperCamelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : Any ) -> None: '''simple docstring''' if index < 0 or index > len(self ): raise IndexError('''list index out of range.''' ) __UpperCamelCase =Node(UpperCamelCase__ ) if self.head is None: __UpperCamelCase =new_node # first node points itself __UpperCamelCase =__UpperCamelCase =new_node elif index == 0: # insert at head __UpperCamelCase =self.head __UpperCamelCase =__UpperCamelCase =new_node else: __UpperCamelCase =self.head for _ in range(index - 1 ): __UpperCamelCase =temp.next __UpperCamelCase =temp.next __UpperCamelCase =new_node if index == len(self ) - 1: # insert at tail __UpperCamelCase =new_node def UpperCAmelCase_ ( self : Any ) -> Any: '''simple docstring''' return self.delete_nth(0 ) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def UpperCAmelCase_ ( self : int , UpperCamelCase__ : int = 0 ) -> Any: '''simple docstring''' if not 0 <= index < len(self ): raise IndexError('''list index out of range.''' ) __UpperCamelCase =self.head if self.head == self.tail: # just one node __UpperCamelCase =__UpperCamelCase =None elif index == 0: # delete head node __UpperCamelCase =self.tail.next.next __UpperCamelCase =self.head.next else: __UpperCamelCase =self.head for _ in range(index - 1 ): __UpperCamelCase =temp.next __UpperCamelCase =temp.next __UpperCamelCase =temp.next.next if index == len(self ) - 1: # delete at tail __UpperCamelCase =temp return delete_node.data def UpperCAmelCase_ ( self : str ) -> bool: '''simple docstring''' return len(self ) == 0 def lowerCAmelCase (): """simple docstring""" __UpperCamelCase =CircularLinkedList() assert len(__UpperCamelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(__UpperCamelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(__UpperCamelCase ) == i circular_linked_list.insert_nth(__UpperCamelCase , i + 1 ) assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
85
1
"""simple docstring""" # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : Tuple , __lowerCAmelCase : bool = True ): """simple docstring""" _lowerCamelCase : dict[T, list[T]] = {} # dictionary of lists _lowerCamelCase : Any = directed def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T , __lowerCAmelCase : T ): """simple docstring""" if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(__lowerCAmelCase ) self.adj_list[destination_vertex].append(__lowerCAmelCase ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(__lowerCAmelCase ) _lowerCamelCase : List[Any] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: _lowerCamelCase : Any = [destination_vertex] _lowerCamelCase : Optional[int] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(__lowerCAmelCase ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: _lowerCamelCase : List[Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: _lowerCamelCase : Any = [destination_vertex] _lowerCamelCase : List[str] = [] return self def __repr__( self : Dict ): """simple docstring""" return pformat(self.adj_list )
72
"""simple docstring""" import math from numpy import inf from scipy.integrate import quad def lowerCamelCase_ (UpperCamelCase__ : float ): if num <= 0: raise ValueError('''math domain error''' ) return quad(UpperCamelCase__ , 0 , UpperCamelCase__ , args=(UpperCamelCase__) )[0] def lowerCamelCase_ (UpperCamelCase__ : float , UpperCamelCase__ : float ): return math.pow(UpperCamelCase__ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
263
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } _UpperCAmelCase = { 'albert-base-v1': 5_1_2, 'albert-large-v1': 5_1_2, 'albert-xlarge-v1': 5_1_2, 'albert-xxlarge-v1': 5_1_2, 'albert-base-v2': 5_1_2, 'albert-large-v2': 5_1_2, 'albert-xlarge-v2': 5_1_2, 'albert-xxlarge-v2': 5_1_2, } _UpperCAmelCase = '▁' class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[int] = VOCAB_FILES_NAMES _UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self: str , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , _SCREAMING_SNAKE_CASE: Any=False , _SCREAMING_SNAKE_CASE: List[Any]="[CLS]" , _SCREAMING_SNAKE_CASE: Tuple="[SEP]" , _SCREAMING_SNAKE_CASE: List[Any]="<unk>" , _SCREAMING_SNAKE_CASE: str="[SEP]" , _SCREAMING_SNAKE_CASE: Any="<pad>" , _SCREAMING_SNAKE_CASE: Dict="[CLS]" , _SCREAMING_SNAKE_CASE: Any="[MASK]" , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: List[str] , ) -> None: """simple docstring""" UpperCamelCase_ = ( AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE , normalized=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token ) UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = do_lower_case UpperCamelCase_ = remove_space UpperCamelCase_ = keep_accents UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: int ) -> List[str]: """simple docstring""" return len(self.sp_model ) def lowercase ( self: Dict ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Any ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: int , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> str: """simple docstring""" if self.remove_space: UpperCamelCase_ = " ".join(inputs.strip().split() ) else: UpperCamelCase_ = inputs UpperCamelCase_ = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: UpperCamelCase_ = unicodedata.normalize("NFKD" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "".join([c for c in outputs if not unicodedata.combining(_SCREAMING_SNAKE_CASE )] ) if self.do_lower_case: UpperCamelCase_ = outputs.lower() return outputs def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" UpperCamelCase_ = self.preprocess_text(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [] for piece in pieces: if len(_SCREAMING_SNAKE_CASE ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): UpperCamelCase_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(_SCREAMING_SNAKE_CASE , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: UpperCamelCase_ = cur_pieces[1:] else: UpperCamelCase_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_SCREAMING_SNAKE_CASE ) else: new_pieces.append(_SCREAMING_SNAKE_CASE ) return new_pieces def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Union[str, Any]: """simple docstring""" return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any] ) -> List[Any]: """simple docstring""" return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Dict ) -> List[str]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" UpperCamelCase_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = True UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = False out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCamelCase_ = [self.sep_token_id] UpperCamelCase_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: Optional[List[int]] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_SCREAMING_SNAKE_CASE , token_ids_a=_SCREAMING_SNAKE_CASE , already_has_special_tokens=_SCREAMING_SNAKE_CASE ) if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCamelCase_ = [self.sep_token_id] UpperCamelCase_ = [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 lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py _lowercase : Optional[Any] = "src/diffusers" # Matches is_xxx_available() _lowercase : Tuple = re.compile(r"is\_([a-z_]*)_available\(\)") # Matches from xxx import bla _lowercase : Optional[int] = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") _lowercase : str = "\n{0} = None\n" _lowercase : List[str] = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n" _lowercase : Union[str, Any] = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" def snake_case__ ( __lowerCamelCase : Union[str, Any] ): """simple docstring""" lowerCamelCase__ : List[str] =_re_backend.findall(__lowerCamelCase ) if len(__lowerCamelCase ) == 0: return None return "_and_".join(__lowerCamelCase ) def snake_case__ ( ): """simple docstring""" with open(os.path.join(__lowerCamelCase , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowerCamelCase__ : List[str] =f.readlines() # Get to the point we do the actual imports for type checking lowerCamelCase__ : Union[str, Any] =0 lowerCamelCase__ : List[str] ={} # Go through the end of the file while line_index < len(__lowerCamelCase ): # If the line contains is_backend_available, we grab all objects associated with the `else` block lowerCamelCase__ : int =find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('''else:''' ): line_index += 1 line_index += 1 lowerCamelCase__ : Optional[Any] =[] # Until we unindent, add backend objects to the list while line_index < len(__lowerCamelCase ) and len(lines[line_index] ) > 1: lowerCamelCase__ : Any =lines[line_index] lowerCamelCase__ : Any =_re_single_line_import.search(__lowerCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(__lowerCamelCase ) > 0: lowerCamelCase__ : Tuple =objects else: line_index += 1 return backend_specific_objects def snake_case__ ( __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] ): """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(__lowerCamelCase ) elif name.islower(): return DUMMY_FUNCTION.format(__lowerCamelCase , __lowerCamelCase ) else: return DUMMY_CLASS.format(__lowerCamelCase , __lowerCamelCase ) def snake_case__ ( __lowerCamelCase : Union[str, Any]=None ): """simple docstring""" if backend_specific_objects is None: lowerCamelCase__ : Optional[Any] =read_init() # For special correspondence backend to module name as used in the function requires_modulename lowerCamelCase__ : int ={} for backend, objects in backend_specific_objects.items(): lowerCamelCase__ : Optional[int] ='''[''' + ''', '''.join(f'''"{b}"''' for b in backend.split('''_and_''' ) ) + ''']''' lowerCamelCase__ : Optional[Any] ='''# This file is autogenerated by the command `make fix-copies`, do not edit.\n''' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(__lowerCamelCase , __lowerCamelCase ) for o in objects] ) lowerCamelCase__ : Dict =dummy_file return dummy_files def snake_case__ ( __lowerCamelCase : List[Any]=False ): """simple docstring""" lowerCamelCase__ : Optional[Any] =create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py lowerCamelCase__ : Optional[Any] ={'''torch''': '''pt'''} # Locate actual dummy modules and read their content. lowerCamelCase__ : int =os.path.join(__lowerCamelCase , '''utils''' ) lowerCamelCase__ : Union[str, Any] ={ backend: os.path.join(__lowerCamelCase , f'''dummy_{short_names.get(__lowerCamelCase , __lowerCamelCase )}_objects.py''' ) for backend in dummy_files.keys() } lowerCamelCase__ : int ={} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(__lowerCamelCase ): with open(__lowerCamelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowerCamelCase__ : List[str] =f.read() else: lowerCamelCase__ : Dict ='''''' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'''Updating diffusers.utils.dummy_{short_names.get(__lowerCamelCase , __lowerCamelCase )}_objects.py as the main ''' '''__init__ has new objects.''' ) with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( '''The main __init__ has objects that are not present in ''' f'''diffusers.utils.dummy_{short_names.get(__lowerCamelCase , __lowerCamelCase )}_objects.py. Run `make fix-copies` ''' '''to fix this.''' ) if __name__ == "__main__": _lowercase : List[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowercase : Tuple = parser.parse_args() check_dummies(args.fix_and_overwrite)
238
"""simple docstring""" import argparse import os import re _lowercase : str = "src/diffusers" # Pattern that looks at the indentation in a line. _lowercase : List[Any] = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowercase : int = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowercase : Optional[int] = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowercase : List[Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowercase : str = re.compile(r"\[([^\]]+)\]") def snake_case__ ( __lowerCamelCase : Optional[int] ): """simple docstring""" lowerCamelCase__ : List[str] =_re_indent.search(__lowerCamelCase ) return "" if search is None else search.groups()[0] def snake_case__ ( __lowerCamelCase : Any , __lowerCamelCase : List[Any]="" , __lowerCamelCase : int=None , __lowerCamelCase : Optional[int]=None ): """simple docstring""" lowerCamelCase__ : Optional[int] =0 lowerCamelCase__ : Any =code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__lowerCamelCase ): index += 1 lowerCamelCase__ : Dict =['''\n'''.join(lines[:index] )] else: lowerCamelCase__ : Tuple =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase__ : int =[lines[index]] index += 1 while index < len(__lowerCamelCase ) and (end_prompt is None or not lines[index].startswith(__lowerCamelCase )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__lowerCamelCase ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__lowerCamelCase ) ) if index < len(__lowerCamelCase ) - 1: lowerCamelCase__ : str =[lines[index + 1]] index += 1 else: lowerCamelCase__ : str =[] else: blocks.append('''\n'''.join(__lowerCamelCase ) ) lowerCamelCase__ : str =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__lowerCamelCase ) > 0: blocks.append('''\n'''.join(__lowerCamelCase ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__lowerCamelCase ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def snake_case__ ( __lowerCamelCase : Any ): """simple docstring""" def _inner(__lowerCamelCase : Any ): return key(__lowerCamelCase ).lower().replace('''_''' , '''''' ) return _inner def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : Any=None ): """simple docstring""" # If no key is provided, we use a noop. def noop(__lowerCamelCase : List[str] ): return x if key is None: lowerCamelCase__ : Tuple =noop # Constants are all uppercase, they go first. lowerCamelCase__ : Union[str, Any] =[obj for obj in objects if key(__lowerCamelCase ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase__ : Optional[int] =[obj for obj in objects if key(__lowerCamelCase )[0].isupper() and not key(__lowerCamelCase ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase__ : Optional[Any] =[obj for obj in objects if not key(__lowerCamelCase )[0].isupper()] lowerCamelCase__ : int =ignore_underscore(__lowerCamelCase ) return sorted(__lowerCamelCase , key=__lowerCamelCase ) + sorted(__lowerCamelCase , key=__lowerCamelCase ) + sorted(__lowerCamelCase , key=__lowerCamelCase ) def snake_case__ ( __lowerCamelCase : Optional[Any] ): """simple docstring""" # This inner function sort imports between [ ]. def _replace(__lowerCamelCase : Optional[Any] ): lowerCamelCase__ : Dict =match.groups()[0] if "," not in imports: return f'''[{imports}]''' lowerCamelCase__ : List[Any] =[part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase__ : Optional[int] =keys[:-1] return "[" + ", ".join([f'''"{k}"''' for k in sort_objects(__lowerCamelCase )] ) + "]" lowerCamelCase__ : List[Any] =import_statement.split('''\n''' ) if len(__lowerCamelCase ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase__ : Tuple =2 if lines[1].strip() == '''[''' else 1 lowerCamelCase__ : Any =[(i, _re_strip_line.search(__lowerCamelCase ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase__ : List[Any] =sort_objects(__lowerCamelCase , key=lambda __lowerCamelCase : x[1] ) lowerCamelCase__ : Union[str, Any] =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__lowerCamelCase ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase__ : List[str] =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase__ : str =[part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase__ : Any =keys[:-1] lowerCamelCase__ : List[Any] =get_indent(lines[1] ) + ''', '''.join([f'''"{k}"''' for k in sort_objects(__lowerCamelCase )] ) return "\n".join(__lowerCamelCase ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase__ : Union[str, Any] =_re_bracket_content.sub(_replace , __lowerCamelCase ) return import_statement def snake_case__ ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any]=True ): """simple docstring""" with open(__lowerCamelCase , '''r''' ) as f: lowerCamelCase__ : Optional[int] =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase__ : int =split_code_in_indented_blocks( __lowerCamelCase , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__lowerCamelCase ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase__ : Optional[Any] =main_blocks[block_idx] lowerCamelCase__ : List[str] =block.split('''\n''' ) # Get to the start of the imports. lowerCamelCase__ : Any =0 while line_idx < len(__lowerCamelCase ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase__ : Tuple =len(__lowerCamelCase ) else: line_idx += 1 if line_idx >= len(__lowerCamelCase ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase__ : Any ='''\n'''.join(block_lines[line_idx:-1] ) lowerCamelCase__ : Dict =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase__ : List[Any] =split_code_in_indented_blocks(__lowerCamelCase , indent_level=__lowerCamelCase ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase__ : List[Any] =_re_direct_key if '''_import_structure''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase__ : Union[str, Any] =[(pattern.search(__lowerCamelCase ).groups()[0] if pattern.search(__lowerCamelCase ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase__ : Optional[Any] =[(i, key) for i, key in enumerate(__lowerCamelCase ) if key is not None] lowerCamelCase__ : List[Any] =[x[0] for x in sorted(__lowerCamelCase , key=lambda __lowerCamelCase : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase__ : Optional[Any] =0 lowerCamelCase__ : Tuple =[] for i in range(len(__lowerCamelCase ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase__ : List[Any] =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(__lowerCamelCase ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase__ : str ='''\n'''.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(__lowerCamelCase ): if check_only: return True else: print(f'''Overwriting {file}.''' ) with open(__lowerCamelCase , '''w''' ) as f: f.write('''\n'''.join(__lowerCamelCase ) ) def snake_case__ ( __lowerCamelCase : Optional[Any]=True ): """simple docstring""" lowerCamelCase__ : Any =[] for root, _, files in os.walk(__lowerCamelCase ): if "__init__.py" in files: lowerCamelCase__ : Tuple =sort_imports(os.path.join(__lowerCamelCase , '''__init__.py''' ) , check_only=__lowerCamelCase ) if result: lowerCamelCase__ : List[str] =[os.path.join(__lowerCamelCase , '''__init__.py''' )] if len(__lowerCamelCase ) > 0: raise ValueError(f'''Would overwrite {len(__lowerCamelCase )} files, run `make style`.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowercase : List[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
238
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class UpperCAmelCase ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE (self : Any ) -> Union[str, Any]: '''simple docstring''' snake_case : Optional[Any] = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] ) snake_case : Union[str, Any] = get_activation("gelu" ) self.assertTrue(torch.allclose(gelu_python(snake_case__ ) , torch_builtin(snake_case__ ) ) ) self.assertFalse(torch.allclose(gelu_python(snake_case__ ) , gelu_new(snake_case__ ) ) ) def _SCREAMING_SNAKE_CASE (self : Tuple ) -> int: '''simple docstring''' snake_case : str = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] ) snake_case : str = get_activation("gelu" ) snake_case : Union[str, Any] = get_activation("gelu_10" ) snake_case : str = torch_builtin(snake_case__ ) snake_case : Optional[int] = geluaa(snake_case__ ) snake_case : Optional[int] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(snake_case__ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Dict: '''simple docstring''' get_activation("gelu" ) get_activation("gelu_10" ) get_activation("gelu_fast" ) get_activation("gelu_new" ) get_activation("gelu_python" ) get_activation("gelu_pytorch_tanh" ) get_activation("linear" ) get_activation("mish" ) get_activation("quick_gelu" ) get_activation("relu" ) get_activation("sigmoid" ) get_activation("silu" ) get_activation("swish" ) get_activation("tanh" ) with self.assertRaises(snake_case__ ): get_activation("bogus" ) with self.assertRaises(snake_case__ ): get_activation(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Any ) -> str: '''simple docstring''' snake_case : int = get_activation("gelu" ) snake_case : str = 1 snake_case : Tuple = get_activation("gelu" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(snake_case__ ): snake_case : Tuple = acta.a
355
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str ): if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("String lengths must match!" ) snake_case : Optional[Any] = 0 for chara, chara in zip(__lowerCamelCase , __lowerCamelCase ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
10
0
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __SCREAMING_SNAKE_CASE (*SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = list(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): snake_case_ = 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 __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = [ '''CUDA out of memory.''', # CUDA OOM '''cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.''', # CUDNN SNAFU '''DefaultCPUAllocator: can\'t allocate memory''', # CPU OOM ] if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 128 ): if function is None: return functools.partial(SCREAMING_SNAKE_CASE__ , starting_batch_size=SCREAMING_SNAKE_CASE__ ) snake_case_ = starting_batch_size def decorator(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): 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_ = list(inspect.signature(SCREAMING_SNAKE_CASE__ ).parameters.keys() ) # Guard against user error if len(SCREAMING_SNAKE_CASE__ ) < (len(SCREAMING_SNAKE_CASE__ ) + 1): snake_case_ = ''', '''.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(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) except Exception as e: if should_reduce_batch_size(SCREAMING_SNAKE_CASE__ ): 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
8
0
'''simple docstring''' from __future__ import annotations _SCREAMING_SNAKE_CASE = list[tuple[int, int]] _SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _SCREAMING_SNAKE_CASE = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class _lowerCAmelCase : """simple docstring""" def __init__( self : Optional[int] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : float , __snake_case : Node | None , )-> Union[str, Any]: snake_case = pos_x snake_case = pos_y snake_case = (pos_y, pos_x) snake_case = goal_x snake_case = goal_y snake_case = g_cost snake_case = parent snake_case = self.calculate_heuristic() def lowerCAmelCase ( self : List[Any] )-> float: snake_case = abs(self.pos_x - self.goal_x ) snake_case = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self : Any , __snake_case : Union[str, Any] )-> bool: return self.f_cost < other.f_cost class _lowerCAmelCase : """simple docstring""" def __init__( self : List[str] , __snake_case : tuple[int, int] , __snake_case : tuple[int, int] )-> Optional[Any]: snake_case = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __snake_case ) snake_case = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , __snake_case ) snake_case = [self.start] snake_case = [] snake_case = False def lowerCAmelCase ( self : Optional[int] )-> Path | None: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() snake_case = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: snake_case = True return self.retrace_path(__snake_case ) self.closed_nodes.append(__snake_case ) snake_case = self.get_successors(__snake_case ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(__snake_case ) else: # retrieve the best current path snake_case = self.open_nodes.pop(self.open_nodes.index(__snake_case ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(__snake_case ) else: self.open_nodes.append(__snake_case ) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str , __snake_case : Node )-> list[Node]: snake_case = [] for action in delta: snake_case = parent.pos_x + action[1] snake_case = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__snake_case ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( __snake_case , __snake_case , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __snake_case , ) ) return successors def lowerCAmelCase ( self : Union[str, Any] , __snake_case : Node | None )-> Path: snake_case = node snake_case = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) snake_case = current_node.parent path.reverse() return path if __name__ == "__main__": _SCREAMING_SNAKE_CASE = (0, 0) _SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") _SCREAMING_SNAKE_CASE = GreedyBestFirst(init, goal) _SCREAMING_SNAKE_CASE = greedy_bf.search() if path: for pos_x, pos_y in path: _SCREAMING_SNAKE_CASE = 2 for elem in grid: print(elem)
3
'''simple docstring''' class _lowerCAmelCase : """simple docstring""" def __init__( self : Optional[Any] , __snake_case : int , __snake_case : Optional[Any]=None , __snake_case : int=None )-> str: snake_case = data snake_case = previous snake_case = next_node def __str__( self : Union[str, Any] )-> str: return f'''{self.data}''' def lowerCAmelCase ( self : Tuple )-> int: return self.data def lowerCAmelCase ( self : str )-> str: return self.next def lowerCAmelCase ( self : Dict )-> Optional[int]: return self.previous class _lowerCAmelCase : """simple docstring""" def __init__( self : int , __snake_case : List[Any] )-> List[str]: snake_case = head def __iter__( self : Optional[int] )-> Dict: return self def lowerCAmelCase ( self : Optional[Any] )-> List[str]: if not self.current: raise StopIteration else: snake_case = self.current.get_data() snake_case = self.current.get_next() return value class _lowerCAmelCase : """simple docstring""" def __init__( self : List[Any] )-> str: snake_case = None # First node in list snake_case = None # Last node in list def __str__( self : List[str] )-> Any: snake_case = self.head snake_case = [] while current is not None: nodes.append(current.get_data() ) snake_case = current.get_next() return " ".join(str(__snake_case ) for node in nodes ) def __contains__( self : Optional[Any] , __snake_case : int )-> Optional[Any]: snake_case = self.head while current: if current.get_data() == value: return True snake_case = current.get_next() return False def __iter__( self : Dict )-> List[Any]: return LinkedListIterator(self.head ) def lowerCAmelCase ( self : Tuple )-> int: if self.head: return self.head.get_data() return None def lowerCAmelCase ( self : Dict )-> Optional[Any]: if self.tail: return self.tail.get_data() return None def lowerCAmelCase ( self : List[Any] , __snake_case : Node )-> None: if self.head is None: snake_case = node snake_case = node else: self.insert_before_node(self.head , __snake_case ) def lowerCAmelCase ( self : int , __snake_case : Node )-> None: if self.head is None: self.set_head(__snake_case ) else: self.insert_after_node(self.tail , __snake_case ) def lowerCAmelCase ( self : str , __snake_case : int )-> None: snake_case = Node(__snake_case ) if self.head is None: self.set_head(__snake_case ) else: self.set_tail(__snake_case ) def lowerCAmelCase ( self : List[Any] , __snake_case : Node , __snake_case : Node )-> None: snake_case = node snake_case = node.previous if node.get_previous() is None: snake_case = node_to_insert else: snake_case = node_to_insert snake_case = node_to_insert def lowerCAmelCase ( self : Optional[int] , __snake_case : Node , __snake_case : Node )-> None: snake_case = node snake_case = node.next if node.get_next() is None: snake_case = node_to_insert else: snake_case = node_to_insert snake_case = node_to_insert def lowerCAmelCase ( self : int , __snake_case : int , __snake_case : int )-> None: snake_case = 1 snake_case = Node(__snake_case ) snake_case = self.head while node: if current_position == position: self.insert_before_node(__snake_case , __snake_case ) return current_position += 1 snake_case = node.next self.insert_after_node(self.tail , __snake_case ) def lowerCAmelCase ( self : str , __snake_case : int )-> Node: snake_case = self.head while node: if node.get_data() == item: return node snake_case = node.get_next() raise Exception("""Node not found""" ) def lowerCAmelCase ( self : Any , __snake_case : Dict )-> Tuple: if (node := self.get_node(__snake_case )) is not None: if node == self.head: snake_case = self.head.get_next() if node == self.tail: snake_case = self.tail.get_previous() self.remove_node_pointers(__snake_case ) @staticmethod def lowerCAmelCase ( __snake_case : Node )-> None: if node.get_next(): snake_case = node.previous if node.get_previous(): snake_case = node.next snake_case = None snake_case = None def lowerCAmelCase ( self : List[Any] )-> Optional[Any]: return self.head is None def __lowerCamelCase ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
3
1
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position lowercase__ :int = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip lowercase__ :Tuple = concatenate_datasets lowercase__ :List[str] = DownloadConfig lowercase__ :Optional[int] = DownloadManager lowercase__ :Optional[int] = DownloadMode lowercase__ :Any = DownloadConfig lowercase__ :str = DownloadMode lowercase__ :List[str] = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
101
'''simple docstring''' from __future__ import annotations from random import choice def UpperCAmelCase_ (__a : str ): """simple docstring""" return choice(__a ) def UpperCAmelCase_ (__a : list[int] , __a : int ): """simple docstring""" _a : Dict = random_pivot(__a ) # partition based on pivot # linear time _a : Optional[int] = [e for e in lst if e < pivot] _a : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
271
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ ): """simple docstring""" if not isinstance(lowercase__ , lowercase__ ): raise ValueError("iterations must be defined as integers" ) if not isinstance(lowercase__ , lowercase__ ) or not number >= 1: raise ValueError( "starting number must be\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) A = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(lowercase__ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
354
"""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 __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" # Load configuration defined in the metadata file with open(lowercase__ ) as metadata_file: A = json.load(lowercase__ ) A = LukeConfig(use_entity_aware_attention=lowercase__ , **metadata["model_config"] ) # Load in the weights from the checkpoint_path A = torch.load(lowercase__ , map_location="cpu" ) # Load the entity vocab file A = load_entity_vocab(lowercase__ ) A = RobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks A = AddedToken("<ent>" , lstrip=lowercase__ , rstrip=lowercase__ ) A = AddedToken("<ent2>" , lstrip=lowercase__ , rstrip=lowercase__ ) 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(lowercase__ ) with open(os.path.join(lowercase__ , LukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) A = LukeTokenizer.from_pretrained(lowercase__ ) # Initialize the embeddings of the special tokens A = state_dict["embeddings.word_embeddings.weight"] A = word_emb[tokenizer.convert_tokens_to_ids(["@"] )[0]].unsqueeze(0 ) A = word_emb[tokenizer.convert_tokens_to_ids(["#"] )[0]].unsqueeze(0 ) A = 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"]: A = F"""encoder.layer.{layer_index}.attention.self.""" A = state_dict[prefix + matrix_name] A = state_dict[prefix + matrix_name] A = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks A = state_dict["entity_embeddings.entity_embeddings.weight"] A = entity_emb[entity_vocab["[MASK]"]] A = LukeModel(config=lowercase__ ).eval() A , A = model.load_state_dict(lowercase__ , strict=lowercase__ ) if not (len(lowercase__ ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F"""Missing keys {", ".join(lowercase__ )}. 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 A = LukeTokenizer.from_pretrained(lowercase__ , task="entity_classification" ) A = ( "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 ." ) A = (39, 42) A = tokenizer(lowercase__ , entity_spans=[span] , add_prefix_space=lowercase__ , return_tensors="pt" ) A = model(**lowercase__ ) # Verify word hidden states if model_size == "large": A = torch.Size((1, 42, 1_024) ) A = torch.tensor( [[0.01_33, 0.08_65, 0.00_95], [0.30_93, -0.25_76, -0.74_18], [-0.17_20, -0.21_17, -0.28_69]] ) else: # base A = torch.Size((1, 42, 768) ) A = torch.tensor([[0.00_37, 0.13_68, -0.00_91], [0.10_99, 0.33_29, -0.10_95], [0.07_65, 0.53_35, 0.11_79]] ) 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] , lowercase__ , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": A = torch.Size((1, 1, 1_024) ) A = torch.tensor([[0.04_66, -0.01_06, -0.01_79]] ) else: # base A = torch.Size((1, 1, 768) ) A = torch.tensor([[0.14_57, 0.10_44, 0.01_74]] ) 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] , lowercase__ , atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(lowercase__ ) ) model.save_pretrained(lowercase__ ) def __SCREAMING_SNAKE_CASE ( lowercase__ ): """simple docstring""" A = {} with open(lowercase__ , "r" , encoding="utf-8" ) as f: for index, line in enumerate(lowercase__ ): A , A = line.rstrip().split("\t" ) A = index return entity_vocab if __name__ == "__main__": __A : Optional[Any] = 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 : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
57
0
'''simple docstring''' from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig __snake_case =logging.get_logger(__name__) # General docstring __snake_case ="""RegNetConfig""" # Base docstring __snake_case ="""facebook/regnet-y-040""" __snake_case =[1, 1_088, 7, 7] # Image classification docstring __snake_case ="""facebook/regnet-y-040""" __snake_case ="""tabby, tabby cat""" __snake_case =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase_ ( nn.Module ): def __init__( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , ) -> Any: super().__init__() lowerCAmelCase = nn.Convad( UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , stride=UpperCAmelCase__ , padding=kernel_size // 2 , groups=UpperCAmelCase__ , bias=UpperCAmelCase__ , ) lowerCAmelCase = nn.BatchNormad(UpperCAmelCase__ ) lowerCAmelCase = ACTaFN[activation] if activation is not None else nn.Identity() def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : Tuple ) -> Tuple: lowerCAmelCase = self.convolution(UpperCAmelCase__ ) lowerCAmelCase = self.normalization(UpperCAmelCase__ ) lowerCAmelCase = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Optional[int] , UpperCAmelCase__ : RegNetConfig ) -> Tuple: super().__init__() lowerCAmelCase = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowerCAmelCase = config.num_channels def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] ) -> Any: lowerCAmelCase = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) lowerCAmelCase = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 ) -> Optional[int]: super().__init__() lowerCAmelCase = nn.Convad(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 , stride=UpperCAmelCase__ , bias=UpperCAmelCase__ ) lowerCAmelCase = nn.BatchNormad(UpperCAmelCase__ ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : Tensor ) -> Tensor: lowerCAmelCase = self.convolution(UpperCAmelCase__ ) lowerCAmelCase = self.normalization(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: super().__init__() lowerCAmelCase = nn.AdaptiveAvgPoolad((1, 1) ) lowerCAmelCase = nn.Sequential( nn.Convad(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 ) , nn.ReLU() , nn.Convad(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 ) , nn.Sigmoid() , ) def __UpperCAmelCase ( self : Tuple , UpperCAmelCase__ : str ) -> Optional[Any]: # b c h w -> b c 1 1 lowerCAmelCase = self.pooler(UpperCAmelCase__ ) lowerCAmelCase = self.attention(UpperCAmelCase__ ) lowerCAmelCase = hidden_state * attention return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Optional[int] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 ) -> Optional[int]: super().__init__() lowerCAmelCase = in_channels != out_channels or stride != 1 lowerCAmelCase = max(1 , out_channels // config.groups_width ) lowerCAmelCase = ( RegNetShortCut(UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ ) if should_apply_shortcut else nn.Identity() ) lowerCAmelCase = nn.Sequential( RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act ) , RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ ) , ) lowerCAmelCase = ACTaFN[config.hidden_act] def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : Any ) -> Union[str, Any]: lowerCAmelCase = hidden_state lowerCAmelCase = self.layer(UpperCAmelCase__ ) lowerCAmelCase = self.shortcut(UpperCAmelCase__ ) hidden_state += residual lowerCAmelCase = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 ) -> Optional[Any]: super().__init__() lowerCAmelCase = in_channels != out_channels or stride != 1 lowerCAmelCase = max(1 , out_channels // config.groups_width ) lowerCAmelCase = ( RegNetShortCut(UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ ) if should_apply_shortcut else nn.Identity() ) lowerCAmelCase = nn.Sequential( RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act ) , RegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ ) , ) lowerCAmelCase = ACTaFN[config.hidden_act] def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : Union[str, Any] ) -> Tuple: lowerCAmelCase = hidden_state lowerCAmelCase = self.layer(UpperCAmelCase__ ) lowerCAmelCase = self.shortcut(UpperCAmelCase__ ) hidden_state += residual lowerCAmelCase = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , ) -> Optional[Any]: super().__init__() lowerCAmelCase = RegNetXLayer if config.layer_type == 'x' else RegNetYLayer lowerCAmelCase = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , ) , *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) for _ in range(depth - 1 )] , ) def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : List[str] ) -> Tuple: lowerCAmelCase = self.layers(UpperCAmelCase__ ) return hidden_state class UpperCAmelCase_ ( nn.Module ): def __init__( self : Any , UpperCAmelCase__ : RegNetConfig ) -> Dict: super().__init__() lowerCAmelCase = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowerCAmelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(UpperCAmelCase__ , config.depths[1:] ): self.stages.append(RegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ ) ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> BaseModelOutputWithNoAttention: lowerCAmelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase = hidden_states + (hidden_state,) lowerCAmelCase = stage_module(UpperCAmelCase__ ) if output_hidden_states: lowerCAmelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : List[Any] = RegNetConfig lowerCamelCase : Any = '''regnet''' lowerCamelCase : Any = '''pixel_values''' lowerCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self : List[str] , UpperCAmelCase__ : int ) -> Optional[int]: if isinstance(UpperCAmelCase__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' ) elif isinstance(UpperCAmelCase__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __UpperCAmelCase ( self : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple=False ) -> Any: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCAmelCase = value __snake_case =R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ __snake_case =R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , __lowercase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class UpperCAmelCase_ ( __lowercase ): def __init__( self : List[str] , UpperCAmelCase__ : Optional[int] ) -> List[Any]: super().__init__(UpperCAmelCase__ ) lowerCAmelCase = config lowerCAmelCase = RegNetEmbeddings(UpperCAmelCase__ ) lowerCAmelCase = RegNetEncoder(UpperCAmelCase__ ) lowerCAmelCase = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None ) -> BaseModelOutputWithPoolingAndNoAttention: lowerCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase = self.embedder(UpperCAmelCase__ ) lowerCAmelCase = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ ) lowerCAmelCase = encoder_outputs[0] lowerCAmelCase = self.pooler(UpperCAmelCase__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , __lowercase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class UpperCAmelCase_ ( __lowercase ): def __init__( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> str: super().__init__(UpperCAmelCase__ ) lowerCAmelCase = config.num_labels lowerCAmelCase = RegNetModel(UpperCAmelCase__ ) # classification head lowerCAmelCase = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self : int , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[torch.LongTensor] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> ImageClassifierOutputWithNoAttention: lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase = self.regnet(UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ ) lowerCAmelCase = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase = self.classifier(UpperCAmelCase__ ) lowerCAmelCase = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCAmelCase = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCAmelCase = 'single_label_classification' else: lowerCAmelCase = 'multi_label_classification' if self.config.problem_type == "regression": lowerCAmelCase = MSELoss() if self.num_labels == 1: lowerCAmelCase = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCAmelCase = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) elif self.config.problem_type == "single_label_classification": lowerCAmelCase = CrossEntropyLoss() lowerCAmelCase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCAmelCase = BCEWithLogitsLoss() lowerCAmelCase = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) if not return_dict: lowerCAmelCase = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
4
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast __lowercase = datasets.utils.logging.get_logger(__name__) @dataclass class _A ( datasets.BuilderConfig ): """simple docstring""" UpperCAmelCase : int = 1_0_0_0_0 UpperCAmelCase : Optional[List[str]] = None UpperCAmelCase : Optional[datasets.Features] = None class _A ( datasets.ArrowBasedBuilder ): """simple docstring""" UpperCAmelCase : str = ParquetConfig def __snake_case ( self : Tuple): return datasets.DatasetInfo(features=self.config.features) def __snake_case ( self : List[Any] , __UpperCAmelCase : str): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''') a : str = dl_manager.download_and_extract(self.config.data_files) if isinstance(__UpperCAmelCase , (str, list, tuple)): a : Dict = data_files if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : str = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive a : List[Any] = [dl_manager.iter_files(__UpperCAmelCase) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files})] a : Dict = [] for split_name, files in data_files.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive a : Tuple = [dl_manager.iter_files(__UpperCAmelCase) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(__UpperCAmelCase): with open(__UpperCAmelCase , "rb") as f: a : Tuple = datasets.Features.from_arrow_schema(pq.read_schema(__UpperCAmelCase)) break splits.append(datasets.SplitGenerator(name=__UpperCAmelCase , gen_kwargs={"files": files})) return splits def __snake_case ( self : List[str] , __UpperCAmelCase : pa.Table): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example a : Optional[int] = table_cast(__UpperCAmelCase , self.info.features.arrow_schema) return pa_table def __snake_case ( self : Union[str, Any] , __UpperCAmelCase : int): a : Tuple = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema) != sorted(self.config.columns): raise ValueError( f'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''') for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase)): with open(__UpperCAmelCase , "rb") as f: a : Tuple = pq.ParquetFile(__UpperCAmelCase) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns)): a : Optional[Any] = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f'''{file_idx}_{batch_idx}''', self._cast_table(__UpperCAmelCase) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(__UpperCAmelCase)}: {e}''') raise
40
0
def UpperCamelCase ( __lowercase : float ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ): raise ValueError('Length must be a positive.' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCamelCase ( __lowercase : float ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ): raise ValueError('Length must be a positive.' ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
366
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor _UpperCAmelCase = logging.get_logger(__name__) class UpperCAmelCase ( __A ): '''simple docstring''' def __init__( self , *lowercase , **lowercase ): """simple docstring""" warnings.warn( 'The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DonutImageProcessor instead.' , lowercase , ) super().__init__(*lowercase , **lowercase )
192
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase : Any = logging.get_logger(__name__) _UpperCAmelCase : Dict = { """google/mobilenet_v2_1.4_224""": """https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json""", """google/mobilenet_v2_1.0_224""": """https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json""", """google/mobilenet_v2_0.75_160""": """https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json""", """google/mobilenet_v2_0.35_96""": """https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json""", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class lowercase ( lowercase_ ): __SCREAMING_SNAKE_CASE : str = '''mobilenet_v2''' def __init__( self , snake_case=3 , snake_case=224 , snake_case=1.0 , snake_case=8 , snake_case=8 , snake_case=6 , snake_case=32 , snake_case=True , snake_case=True , snake_case="relu6" , snake_case=True , snake_case=0.8 , snake_case=0.02 , snake_case=0.0_01 , snake_case=255 , **snake_case , ): super().__init__(**snake_case ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) snake_case_ = num_channels snake_case_ = image_size snake_case_ = depth_multiplier snake_case_ = depth_divisible_by snake_case_ = min_depth snake_case_ = expand_ratio snake_case_ = output_stride snake_case_ = first_layer_is_expansion snake_case_ = finegrained_output snake_case_ = hidden_act snake_case_ = tf_padding snake_case_ = classifier_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = semantic_loss_ignore_index class lowercase ( lowercase_ ): __SCREAMING_SNAKE_CASE : str = version.parse('''1.11''' ) @property def a ( self ): return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def a ( self ): if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def a ( self ): return 1e-4
285
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig _UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) # General docstring _UpperCAmelCase : Dict = """ResNetConfig""" # Base docstring _UpperCAmelCase : Optional[int] = """microsoft/resnet-50""" _UpperCAmelCase : Optional[Any] = [1, 2048, 7, 7] # Image classification docstring _UpperCAmelCase : Tuple = """microsoft/resnet-50""" _UpperCAmelCase : int = """tiger cat""" _UpperCAmelCase : Optional[Any] = [ """microsoft/resnet-50""", # See all resnet models at https://huggingface.co/models?filter=resnet ] class lowercase ( nn.Module ): def __init__( self , snake_case , snake_case , snake_case = 3 , snake_case = 1 , snake_case = "relu" ): super().__init__() snake_case_ = nn.Convad( snake_case , snake_case , kernel_size=snake_case , stride=snake_case , padding=kernel_size // 2 , bias=snake_case ) snake_case_ = nn.BatchNormad(snake_case ) snake_case_ = ACTaFN[activation] if activation is not None else nn.Identity() def a ( self , snake_case ): snake_case_ = self.convolution(snake_case ) snake_case_ = self.normalization(snake_case ) snake_case_ = self.activation(snake_case ) return hidden_state class lowercase ( nn.Module ): def __init__( self , snake_case ): super().__init__() snake_case_ = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) snake_case_ = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) snake_case_ = config.num_channels def a ( self , snake_case ): snake_case_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) snake_case_ = self.embedder(snake_case ) snake_case_ = self.pooler(snake_case ) return embedding class lowercase ( nn.Module ): def __init__( self , snake_case , snake_case , snake_case = 2 ): super().__init__() snake_case_ = nn.Convad(snake_case , snake_case , kernel_size=1 , stride=snake_case , bias=snake_case ) snake_case_ = nn.BatchNormad(snake_case ) def a ( self , snake_case ): snake_case_ = self.convolution(snake_case ) snake_case_ = self.normalization(snake_case ) return hidden_state class lowercase ( nn.Module ): def __init__( self , snake_case , snake_case , snake_case = 1 , snake_case = "relu" ): super().__init__() snake_case_ = in_channels != out_channels or stride != 1 snake_case_ = ( ResNetShortCut(snake_case , snake_case , stride=snake_case ) if should_apply_shortcut else nn.Identity() ) snake_case_ = nn.Sequential( ResNetConvLayer(snake_case , snake_case , stride=snake_case ) , ResNetConvLayer(snake_case , snake_case , activation=snake_case ) , ) snake_case_ = ACTaFN[activation] def a ( self , snake_case ): snake_case_ = hidden_state snake_case_ = self.layer(snake_case ) snake_case_ = self.shortcut(snake_case ) hidden_state += residual snake_case_ = self.activation(snake_case ) return hidden_state class lowercase ( nn.Module ): def __init__( self , snake_case , snake_case , snake_case = 1 , snake_case = "relu" , snake_case = 4 ): super().__init__() snake_case_ = in_channels != out_channels or stride != 1 snake_case_ = out_channels // reduction snake_case_ = ( ResNetShortCut(snake_case , snake_case , stride=snake_case ) if should_apply_shortcut else nn.Identity() ) snake_case_ = nn.Sequential( ResNetConvLayer(snake_case , snake_case , kernel_size=1 ) , ResNetConvLayer(snake_case , snake_case , stride=snake_case ) , ResNetConvLayer(snake_case , snake_case , kernel_size=1 , activation=snake_case ) , ) snake_case_ = ACTaFN[activation] def a ( self , snake_case ): snake_case_ = hidden_state snake_case_ = self.layer(snake_case ) snake_case_ = self.shortcut(snake_case ) hidden_state += residual snake_case_ = self.activation(snake_case ) return hidden_state class lowercase ( nn.Module ): def __init__( self , snake_case , snake_case , snake_case , snake_case = 2 , snake_case = 2 , ): super().__init__() snake_case_ = ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer snake_case_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(snake_case , snake_case , stride=snake_case , activation=config.hidden_act ) , *[layer(snake_case , snake_case , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def a ( self , snake_case ): snake_case_ = input for layer in self.layers: snake_case_ = layer(snake_case ) return hidden_state class lowercase ( nn.Module ): def __init__( self , snake_case ): super().__init__() snake_case_ = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( snake_case , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) snake_case_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(snake_case , config.depths[1:] ): self.stages.append(ResNetStage(snake_case , snake_case , snake_case , depth=snake_case ) ) def a ( self , snake_case , snake_case = False , snake_case = True ): snake_case_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: snake_case_ = hidden_states + (hidden_state,) snake_case_ = stage_module(snake_case ) if output_hidden_states: snake_case_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=snake_case , hidden_states=snake_case , ) class lowercase ( lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = ResNetConfig __SCREAMING_SNAKE_CASE : Any = '''resnet''' __SCREAMING_SNAKE_CASE : int = '''pixel_values''' __SCREAMING_SNAKE_CASE : Tuple = True def a ( self , snake_case ): if isinstance(snake_case , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' ) elif isinstance(snake_case , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def a ( self , snake_case , snake_case=False ): if isinstance(snake_case , snake_case ): snake_case_ = value _UpperCAmelCase : Tuple = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ _UpperCAmelCase : Optional[int] = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare ResNet model outputting raw features without any specific head on top.''' , lowercase_ , ) class lowercase ( lowercase_ ): def __init__( self , snake_case ): super().__init__(snake_case ) snake_case_ = config snake_case_ = ResNetEmbeddings(snake_case ) snake_case_ = ResNetEncoder(snake_case ) snake_case_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(snake_case ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=snake_case , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def a ( self , snake_case , snake_case = None , snake_case = None ): snake_case_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = self.embedder(snake_case ) snake_case_ = self.encoder( snake_case , output_hidden_states=snake_case , return_dict=snake_case ) snake_case_ = encoder_outputs[0] snake_case_ = self.pooler(snake_case ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=snake_case , pooler_output=snake_case , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( ''' ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , lowercase_ , ) class lowercase ( lowercase_ ): def __init__( self , snake_case ): super().__init__(snake_case ) snake_case_ = config.num_labels snake_case_ = ResNetModel(snake_case ) # classification head snake_case_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(snake_case ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=snake_case , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def a ( self , snake_case = None , snake_case = None , snake_case = None , snake_case = None , ): snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = self.resnet(snake_case , output_hidden_states=snake_case , return_dict=snake_case ) snake_case_ = outputs.pooler_output if return_dict else outputs[1] snake_case_ = self.classifier(snake_case ) snake_case_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case_ = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case_ = 'single_label_classification' else: snake_case_ = 'multi_label_classification' if self.config.problem_type == "regression": snake_case_ = MSELoss() if self.num_labels == 1: snake_case_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case_ = loss_fct(snake_case , snake_case ) elif self.config.problem_type == "single_label_classification": snake_case_ = CrossEntropyLoss() snake_case_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case_ = BCEWithLogitsLoss() snake_case_ = loss_fct(snake_case , snake_case ) if not return_dict: snake_case_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=snake_case , logits=snake_case , hidden_states=outputs.hidden_states ) @add_start_docstrings( ''' ResNet backbone, to be used with frameworks like DETR and MaskFormer. ''' , lowercase_ , ) class lowercase ( lowercase_ , lowercase_ ): def __init__( self , snake_case ): super().__init__(snake_case ) super()._init_backbone(snake_case ) snake_case_ = [config.embedding_size] + config.hidden_sizes snake_case_ = ResNetEmbeddings(snake_case ) snake_case_ = ResNetEncoder(snake_case ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(snake_case ) @replace_return_docstrings(output_type=snake_case , config_class=_CONFIG_FOR_DOC ) def a ( self , snake_case , snake_case = None , snake_case = None ): snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ = self.embedder(snake_case ) snake_case_ = self.encoder(snake_case , output_hidden_states=snake_case , return_dict=snake_case ) snake_case_ = outputs.hidden_states snake_case_ = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: snake_case_ = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=snake_case , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=snake_case , )
285
1
def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__lowerCamelCase , n - 1 , __lowerCamelCase ) * a) % mod else: __a = binary_exponentiation(__lowerCamelCase , n / 2 , __lowerCamelCase ) return (b * b) % mod # a prime number lowerCamelCase_ : str = 701 lowerCamelCase_ : Optional[int] = 1_000_000_000 lowerCamelCase_ : Optional[int] = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
197
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class a__ ( __snake_case ): A__ : torch.FloatTensor A__ : torch.FloatTensor A__ : Optional[torch.FloatTensor] = None class a__ ( __snake_case , __snake_case ): A__ : Optional[Any] = 2 @register_to_config def __init__( self , UpperCAmelCase = 0.02 , UpperCAmelCase = 1_0_0 , UpperCAmelCase = 1.007 , UpperCAmelCase = 8_0 , UpperCAmelCase = 0.05 , UpperCAmelCase = 5_0 , ) -> Optional[Any]: # standard deviation of the initial noise distribution __a = sigma_max # setable values __a = None __a = None __a = None # sigma(t_i) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> torch.FloatTensor: return sample def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> int: __a = num_inference_steps __a = np.arange(0 , self.num_inference_steps )[::-1].copy() __a = torch.from_numpy(UpperCAmelCase ).to(UpperCAmelCase ) __a = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __a = torch.tensor(UpperCAmelCase , dtype=torch.floataa , device=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None ) -> Tuple[torch.FloatTensor, float]: if self.config.s_min <= sigma <= self.config.s_max: __a = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: __a = 0 # sample eps ~ N(0, S_noise^2 * I) __a = self.config.s_noise * randn_tensor(sample.shape , generator=UpperCAmelCase ).to(sample.device ) __a = sigma + gamma * sigma __a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: __a = sample_hat + sigma_hat * model_output __a = (sample_hat - pred_original_sample) / sigma_hat __a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: __a = sample_prev + sigma_prev * model_output __a = (sample_prev - pred_original_sample) / sigma_prev __a = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[Any]: raise NotImplementedError()
197
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : List[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } __UpperCamelCase : Tuple = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): for attribute in key.split('''.''' ): SCREAMING_SNAKE_CASE : List[Any] = getattr(__UpperCamelCase , __UpperCamelCase ) if weight_type is not None: SCREAMING_SNAKE_CASE : Any = getattr(__UpperCamelCase , __UpperCamelCase ).shape else: SCREAMING_SNAKE_CASE : Optional[int] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": SCREAMING_SNAKE_CASE : Tuple = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE : List[str] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE : Tuple = value elif weight_type == "bias": SCREAMING_SNAKE_CASE : Tuple = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE : List[str] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE : Tuple = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE : Dict = value elif weight_type == "inv_freq": SCREAMING_SNAKE_CASE : int = value else: SCREAMING_SNAKE_CASE : Dict = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : List[str] = fairseq_model.state_dict() SCREAMING_SNAKE_CASE : Dict = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , hf_model.config.feat_extract_norm == '''group''' , ) SCREAMING_SNAKE_CASE : List[Any] = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE : Union[str, Any] = '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: SCREAMING_SNAKE_CASE : Tuple = True if "*" in mapped_key: SCREAMING_SNAKE_CASE : Dict = name.split(__UpperCamelCase )[0].split('''.''' )[-2] SCREAMING_SNAKE_CASE : Optional[Any] = mapped_key.replace('''*''' , __UpperCamelCase ) if "pos_bias_u" in name: SCREAMING_SNAKE_CASE : List[Any] = None elif "pos_bias_v" in name: SCREAMING_SNAKE_CASE : Optional[Any] = None elif "weight_g" in name: SCREAMING_SNAKE_CASE : List[Any] = '''weight_g''' elif "weight_v" in name: SCREAMING_SNAKE_CASE : List[str] = '''weight_v''' elif "bias" in name: SCREAMING_SNAKE_CASE : List[Any] = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE : List[str] = '''weight''' elif "running_mean" in name: SCREAMING_SNAKE_CASE : Any = '''running_mean''' elif "inv_freq" in name: SCREAMING_SNAKE_CASE : Optional[Any] = '''inv_freq''' elif "running_var" in name: SCREAMING_SNAKE_CASE : Any = '''running_var''' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE : Any = '''num_batches_tracked''' else: SCREAMING_SNAKE_CASE : Optional[Any] = None set_recursively(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) continue if not is_used: unused_weights.append(__UpperCamelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Tuple = full_name.split('''conv_layers.''' )[-1] SCREAMING_SNAKE_CASE : Optional[int] = name.split('''.''' ) SCREAMING_SNAKE_CASE : List[Any] = int(items[0] ) SCREAMING_SNAKE_CASE : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) SCREAMING_SNAKE_CASE : List[str] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) SCREAMING_SNAKE_CASE : int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) SCREAMING_SNAKE_CASE : List[str] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) SCREAMING_SNAKE_CASE : int = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__UpperCamelCase ) @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=True ): if config_path is not None: SCREAMING_SNAKE_CASE : Optional[int] = WavaVecaConformerConfig.from_pretrained(__UpperCamelCase , hidden_act='''swish''' ) else: SCREAMING_SNAKE_CASE : int = WavaVecaConformerConfig() if "rope" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = '''rotary''' if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE : str = Dictionary.load(__UpperCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE : Tuple = target_dict.pad_index SCREAMING_SNAKE_CASE : List[str] = target_dict.bos_index SCREAMING_SNAKE_CASE : Dict = target_dict.eos_index SCREAMING_SNAKE_CASE : str = len(target_dict.symbols ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(__UpperCamelCase , '''vocab.json''' ) if not os.path.isdir(__UpperCamelCase ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__UpperCamelCase ) ) return os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) SCREAMING_SNAKE_CASE : str = target_dict.indices # fairseq has the <pad> and <s> switched SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 1 with open(__UpperCamelCase , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(__UpperCamelCase , __UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = WavaVecaCTCTokenizer( __UpperCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__UpperCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = True if config.feat_extract_norm == '''layer''' else False SCREAMING_SNAKE_CASE : Union[str, Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=__UpperCamelCase , return_attention_mask=__UpperCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = WavaVecaProcessor(feature_extractor=__UpperCamelCase , tokenizer=__UpperCamelCase ) processor.save_pretrained(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaConformerForCTC(__UpperCamelCase ) else: SCREAMING_SNAKE_CASE : int = WavaVecaConformerForPreTraining(__UpperCamelCase ) if is_finetuned: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: SCREAMING_SNAKE_CASE : Optional[int] = argparse.Namespace(task='''audio_pretraining''' ) SCREAMING_SNAKE_CASE : Dict = fairseq.tasks.setup_task(__UpperCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__UpperCamelCase ) SCREAMING_SNAKE_CASE : str = model[0].eval() recursively_load_weights(__UpperCamelCase , __UpperCamelCase , not is_finetuned ) hf_wavavec.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": __UpperCamelCase : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) __UpperCamelCase : Any = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
182
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __snake_case ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = KandinskyVaaImgaImgPipeline lowerCAmelCase_ = ["image_embeds", "negative_image_embeds", "image"] lowerCAmelCase_ = [ "image_embeds", "negative_image_embeds", "image", ] lowerCAmelCase_ = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCAmelCase_ = False @property def __a ( self : Union[str, Any] ): """simple docstring""" return 32 @property def __a ( self : Union[str, Any] ): """simple docstring""" return 32 @property def __a ( self : Optional[Any] ): """simple docstring""" return self.time_input_dim @property def __a ( self : Optional[int] ): """simple docstring""" return self.time_input_dim * 4 @property def __a ( self : List[str] ): """simple docstring""" return 1_00 @property def __a ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } SCREAMING_SNAKE_CASE__ = UNetaDConditionModel(**_lowercase ) return model @property def __a ( self : str ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __a ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = VQModel(**self.dummy_movq_kwargs ) return model def __a ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_unet SCREAMING_SNAKE_CASE__ = self.dummy_movq SCREAMING_SNAKE_CASE__ = { """num_train_timesteps""": 10_00, """beta_schedule""": """linear""", """beta_start""": 0.0_00_85, """beta_end""": 0.0_12, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } SCREAMING_SNAKE_CASE__ = DDIMScheduler(**_lowercase ) SCREAMING_SNAKE_CASE__ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __a ( self : Optional[Any] , _lowercase : Any , _lowercase : Tuple=0 ): """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowercase ) ).to(_lowercase ) SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowercase ) # create init_image SCREAMING_SNAKE_CASE__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowercase ) ).to(_lowercase ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ = Image.fromarray(np.uinta(_lowercase ) ).convert("""RGB""" ).resize((2_56, 2_56) ) if str(_lowercase ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(_lowercase ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) SCREAMING_SNAKE_CASE__ = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**_lowercase ) SCREAMING_SNAKE_CASE__ = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(_lowercase ) ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): def __a ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_img2img_frog.npy""" ) SCREAMING_SNAKE_CASE__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) SCREAMING_SNAKE_CASE__ = """A red cartoon frog, 4k""" SCREAMING_SNAKE_CASE__ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_lowercase ) SCREAMING_SNAKE_CASE__ = KandinskyVaaImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = pipeline.to(_lowercase ) pipeline.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE__ = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = pipe_prior( _lowercase , generator=_lowercase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ = pipeline( image=_lowercase , image_embeds=_lowercase , negative_image_embeds=_lowercase , generator=_lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(_lowercase , _lowercase )
219
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) A_ : List[str] ={"""configuration_beit""": ["""BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BeitConfig""", """BeitOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[str] =["""BeitFeatureExtractor"""] A_ : Dict =["""BeitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Tuple =[ """BEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BeitForImageClassification""", """BeitForMaskedImageModeling""", """BeitForSemanticSegmentation""", """BeitModel""", """BeitPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[str] =[ """FlaxBeitForImageClassification""", """FlaxBeitForMaskedImageModeling""", """FlaxBeitModel""", """FlaxBeitPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys A_ : Optional[Any] =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
80
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor A_ : Union[str, Any] =logging.get_logger(__name__) class __a ( lowerCAmelCase__ ): def __init__( self , *a__ , **a__ ): warnings.warn( 'The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DPTImageProcessor instead.' , a__ , ) super().__init__(*a__ , **a__ )
80
1
'''simple docstring''' import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : int = 1.5 A : Dict = int(factor * num_class_images ) A : Tuple = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=snake_case__ , aesthetic_weight=0.1 ) os.makedirs(F'{class_data_dir}/images' , exist_ok=snake_case__ ) if len(list(Path(F'{class_data_dir}/images' ).iterdir() ) ) >= num_class_images: return while True: A : Tuple = client.query(text=snake_case__ ) if len(snake_case__ ) >= factor * num_class_images or num_images > 1E4: break else: A : Dict = int(factor * num_images ) A : Optional[int] = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=snake_case__ , aesthetic_weight=0.1 , ) A : Dict = 0 A : Optional[int] = 0 A : Tuple = tqdm(desc='''downloading real regularization images''' , total=snake_case__ ) with open(F'{class_data_dir}/caption.txt' , '''w''' ) as fa, open(F'{class_data_dir}/urls.txt' , '''w''' ) as fa, open( F'{class_data_dir}/images.txt' , '''w''' ) as fa: while total < num_class_images: A : Optional[Any] = class_images[count] count += 1 try: A : Dict = requests.get(images['''url'''] ) if img.status_code == 200: A : Tuple = Image.open(BytesIO(img.content ) ) with open(F'{class_data_dir}/images/{total}.jpg' , '''wb''' ) as f: f.write(img.content ) fa.write(images['''caption'''] + '''\n''' ) fa.write(images['''url'''] + '''\n''' ) fa.write(F'{class_data_dir}/images/{total}.jpg' + '''\n''' ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def lowerCAmelCase_ ( ): '''simple docstring''' A : int = argparse.ArgumentParser('''''' , add_help=snake_case__ ) parser.add_argument('''--class_prompt''' , help='''text prompt to retrieve images''' , required=snake_case__ , type=snake_case__ ) parser.add_argument('''--class_data_dir''' , help='''path to save images''' , required=snake_case__ , type=snake_case__ ) parser.add_argument('''--num_class_images''' , help='''number of images to download''' , default=200 , type=snake_case__ ) return parser.parse_args() if __name__ == "__main__": lowercase : Optional[int] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
3
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "microsoft/table-transformer-detection": ( "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json" ), } class __lowercase (_UpperCAmelCase ): _UpperCamelCase = """table-transformer""" _UpperCamelCase = ["""past_key_values"""] _UpperCamelCase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , A_=True , A_=None , A_=3 , A_=100 , A_=6 , A_=2048 , A_=8 , A_=6 , A_=2048 , A_=8 , A_=0.0 , A_=0.0 , A_=True , A_="relu" , A_=256 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=1.0 , A_=False , A_="sine" , A_="resnet50" , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=1 , A_=1 , A_=5 , A_=2 , A_=0.1 , **A_ , ) ->Any: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __lowerCAmelCase : Optional[Any] = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(A_ , A_ ): __lowerCAmelCase : int = backbone_config.get('''model_type''' ) __lowerCAmelCase : List[str] = CONFIG_MAPPING[backbone_model_type] __lowerCAmelCase : Any = config_class.from_dict(A_ ) # set timm attributes to None __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : List[str] = None, None, None __lowerCAmelCase : Tuple = use_timm_backbone __lowerCAmelCase : Optional[Any] = backbone_config __lowerCAmelCase : List[str] = num_channels __lowerCAmelCase : Tuple = num_queries __lowerCAmelCase : int = d_model __lowerCAmelCase : List[Any] = encoder_ffn_dim __lowerCAmelCase : Optional[int] = encoder_layers __lowerCAmelCase : List[str] = encoder_attention_heads __lowerCAmelCase : str = decoder_ffn_dim __lowerCAmelCase : Union[str, Any] = decoder_layers __lowerCAmelCase : Any = decoder_attention_heads __lowerCAmelCase : Optional[int] = dropout __lowerCAmelCase : Any = attention_dropout __lowerCAmelCase : Tuple = activation_dropout __lowerCAmelCase : Optional[Any] = activation_function __lowerCAmelCase : List[str] = init_std __lowerCAmelCase : Tuple = init_xavier_std __lowerCAmelCase : Any = encoder_layerdrop __lowerCAmelCase : List[Any] = decoder_layerdrop __lowerCAmelCase : Optional[Any] = encoder_layers __lowerCAmelCase : Optional[Any] = auxiliary_loss __lowerCAmelCase : Optional[Any] = position_embedding_type __lowerCAmelCase : Tuple = backbone __lowerCAmelCase : Any = use_pretrained_backbone __lowerCAmelCase : int = dilation # Hungarian matcher __lowerCAmelCase : Dict = class_cost __lowerCAmelCase : List[str] = bbox_cost __lowerCAmelCase : int = giou_cost # Loss coefficients __lowerCAmelCase : Optional[Any] = mask_loss_coefficient __lowerCAmelCase : Tuple = dice_loss_coefficient __lowerCAmelCase : int = bbox_loss_coefficient __lowerCAmelCase : List[Any] = giou_loss_coefficient __lowerCAmelCase : int = eos_coefficient super().__init__(is_encoder_decoder=A_ , **A_ ) @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return self.encoder_attention_heads @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return self.d_model class __lowercase (_UpperCAmelCase ): _UpperCamelCase = version.parse("""1.11""" ) @property def UpperCamelCase__ ( self ) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def UpperCamelCase__ ( self ) ->float: '''simple docstring''' return 1e-5 @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return 12
275
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class snake_case : def __init__( self : Tuple , A : Union[str, Any] , A : str=1_3 , A : Dict=7 , A : Tuple=True , A : int=True , A : Dict=True , A : List[str]=True , A : str=9_9 , A : Optional[int]=3_2 , A : Optional[Any]=2 , A : Optional[Any]=4 , A : List[str]=3_7 , A : int="gelu" , A : str=0.1 , A : Union[str, Any]=0.1 , A : str=5_1_2 , A : str=1_6 , A : List[str]=2 , A : Tuple=0.02 , A : Any=False , A : List[Any]=True , A : int="None" , A : str=3 , A : Tuple=4 , A : str=None , ): '''simple docstring''' a : List[Any] = parent a : Any = batch_size a : List[str] = seq_length a : List[Any] = is_training a : Any = use_input_mask a : Union[str, Any] = use_token_type_ids a : Tuple = use_labels a : str = vocab_size a : str = hidden_size a : Union[str, Any] = num_hidden_layers a : Optional[Any] = num_attention_heads a : Tuple = intermediate_size a : Tuple = hidden_act a : Optional[int] = hidden_dropout_prob a : Dict = attention_probs_dropout_prob a : Optional[int] = max_position_embeddings a : Optional[int] = type_vocab_size a : int = type_sequence_label_size a : Any = initializer_range a : Dict = num_labels a : Optional[Any] = num_choices a : List[Any] = relative_attention a : Dict = position_biased_input a : Optional[Any] = pos_att_type a : Dict = scope def lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' a : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Tuple = None if self.use_input_mask: a : str = random_attention_mask([self.batch_size, self.seq_length] ) a : str = None if self.use_token_type_ids: a : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a : List[str] = None a : Union[str, Any] = None a : Union[str, Any] = None if self.use_labels: a : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : str = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Optional[Any] , A : Any , A : str , A : Union[str, Any] , A : Dict , A : Optional[Any] , A : str , A : int ): '''simple docstring''' a : Dict = TFDebertaVaModel(config=A ) a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} a : int = [input_ids, input_mask] a : Union[str, Any] = model(A ) a : Any = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : List[Any] , A : Optional[int] , A : Optional[Any] , A : str , A : List[str] , A : str , A : str , A : Tuple ): '''simple docstring''' a : Any = TFDebertaVaForMaskedLM(config=A ) a : Any = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a : str = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : Any , A : int , A : Optional[Any] , A : Tuple , A : Optional[int] , A : Union[str, Any] , A : Tuple , A : int ): '''simple docstring''' a : str = self.num_labels a : List[Any] = TFDebertaVaForSequenceClassification(config=A ) a : List[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a : str = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Dict , A : List[Any] , A : Optional[int] , A : List[Any] , A : Any , A : Tuple , A : Any , A : Union[str, Any] ): '''simple docstring''' a : List[Any] = self.num_labels a : List[str] = TFDebertaVaForTokenClassification(config=A ) a : Optional[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a : Optional[Any] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : Any , A : Dict , A : str , A : Tuple , A : int , A : Optional[int] , A : Any , A : List[str] ): '''simple docstring''' a : str = TFDebertaVaForQuestionAnswering(config=A ) a : str = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a : str = model(A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' a : int = self.prepare_config_and_inputs() ( ( a ), ( a ), ( a ), ( a ), ( a ), ( a ), ( a ), ) : List[Any] = config_and_inputs a : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class snake_case ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): __magic_name__ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDebertaVaModel, '''fill-mask''': TFDebertaVaForMaskedLM, '''question-answering''': TFDebertaVaForQuestionAnswering, '''text-classification''': TFDebertaVaForSequenceClassification, '''token-classification''': TFDebertaVaForTokenClassification, '''zero-shot''': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False def lowerCamelCase__ ( self : Dict ): '''simple docstring''' a : Tuple = TFDebertaVaModelTester(self ) a : Union[str, Any] = ConfigTester(self , config_class=A , hidden_size=3_7 ) def lowerCamelCase__ ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def lowerCamelCase__ ( self : str ): '''simple docstring''' a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def lowerCamelCase__ ( self : Optional[int] ): '''simple docstring''' a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) @slow def lowerCamelCase__ ( self : Dict ): '''simple docstring''' a : Any = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(A ) @require_tf class snake_case ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def lowerCamelCase__ ( self : str ): '''simple docstring''' pass @slow def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' a : Any = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) a : Union[str, Any] = tf.constant([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) a : List[Any] = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) a : Union[str, Any] = model(A , attention_mask=A )[0] a : List[Any] = tf.constant( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , A , atol=1E-4 )
186
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging _UpperCamelCase : int = logging.get_logger(__name__) class snake_case ( UpperCAmelCase ): __magic_name__ = ['''input_features''', '''attention_mask'''] def __init__( self : Optional[int] , A : Optional[Any]=8_0 , A : str=1_6_0_0_0 , A : List[str]=0.0 , A : Any=1_0 , A : Union[str, Any]=2_5 , A : str="hamming_window" , A : str=3_27_68.0 , A : Union[str, Any]=0.97 , A : Dict=1.0 , A : Any=True , A : Union[str, Any]=True , A : List[Any]=False , **A : Tuple , ): '''simple docstring''' super().__init__(feature_size=A , sampling_rate=A , padding_value=A , **A ) a : Any = feature_size a : List[Any] = sampling_rate a : Any = padding_value a : str = hop_length a : Any = win_length a : List[Any] = frame_signal_scale a : Tuple = preemphasis_coeff a : Dict = mel_floor a : Optional[int] = normalize_means a : List[str] = normalize_vars a : Dict = win_function a : Union[str, Any] = return_attention_mask a : List[Any] = win_length * sampling_rate // 1_0_0_0 a : Tuple = hop_length * sampling_rate // 1_0_0_0 a : List[Any] = optimal_fft_length(self.sample_size ) a : Any = (self.n_fft // 2) + 1 def lowerCamelCase__ ( self : List[Any] , A : np.array ): '''simple docstring''' if self.win_function == "hamming_window": a : List[str] = window_function(window_length=self.sample_size , name=self.win_function , periodic=A ) else: a : Dict = window_function(window_length=self.sample_size , name=self.win_function ) a : str = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) a : List[Any] = spectrogram( one_waveform * self.frame_signal_scale , window=A , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=A , preemphasis=self.preemphasis_coeff , mel_filters=A , mel_floor=self.mel_floor , log_mel='log' , ) return msfc_features.T def lowerCamelCase__ ( self : int , A : Tuple , A : int , A : Optional[int] ): '''simple docstring''' if self.normalize_means: a : Any = x[:input_length].mean(axis=0 ) a : Dict = np.subtract(A , A ) if self.normalize_vars: a : Dict = x[:input_length].std(axis=0 ) a : Dict = np.divide(A , A ) if input_length < x.shape[0]: a : Dict = padding_value # make sure array is in float32 a : Optional[int] = x.astype(np.floataa ) return x def lowerCamelCase__ ( self : str , A : List[np.ndarray] , A : Optional[np.ndarray] = None ): '''simple docstring''' a : str = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(A , A , self.padding_value ) for x, n in zip(A , A )] def __call__( self : Dict , A : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , A : Union[bool, str, PaddingStrategy] = False , A : Optional[int] = None , A : bool = False , A : Optional[int] = None , A : Optional[bool] = None , A : Optional[Union[str, TensorType]] = None , A : Optional[int] = None , **A : Union[str, Any] , ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( 'It is strongly recommended to pass the ``sampling_rate`` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) a : Optional[int] = isinstance(A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) a : Dict = is_batched_numpy or ( isinstance(A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a : str = [np.asarray(A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(A , np.ndarray ): a : List[str] = np.asarray(A , dtype=np.floataa ) elif isinstance(A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a : Optional[int] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a : Any = [raw_speech] # extract fbank features a : str = [self._extract_mfsc_features(A ) for one_waveform in raw_speech] # convert into correct format for padding a : int = BatchFeature({'input_features': features} ) a : Union[str, Any] = self.pad( A , padding=A , max_length=A , truncation=A , pad_to_multiple_of=A , return_attention_mask=A , **A , ) # make sure list is in array format a : Optional[Any] = padded_inputs.get('input_features' ) if isinstance(input_features[0] , A ): a : List[str] = [np.asarray(A , dtype=np.floataa ) for feature in input_features] a : List[Any] = padded_inputs.get('attention_mask' ) if attention_mask is not None: a : int = [np.asarray(A , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: a : Any = ( np.array(A , dtype=np.intaa ) if self._get_padding_strategies(A , max_length=A ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) a : List[str] = self.normalize( padded_inputs['input_features'] , attention_mask=A ) if return_tensors is not None: a : Optional[int] = padded_inputs.convert_to_tensors(A ) return padded_inputs
186
1