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
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "edbeeching/decision-transformer-gym-hopper-medium": ( "https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'decision_transformer' __UpperCAmelCase : int = ['past_key_values'] __UpperCAmelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _a=17 , _a=4 , _a=128 , _a=4_096 , _a=True , _a=1 , _a=1_024 , _a=3 , _a=1 , _a=None , _a="relu" , _a=0.1 , _a=0.1 , _a=0.1 , _a=1E-5 , _a=0.02 , _a=True , _a=True , _a=50_256 , _a=50_256 , _a=False , _a=False , **_a , ): __a = state_dim __a = act_dim __a = hidden_size __a = max_ep_len __a = action_tanh __a = vocab_size __a = n_positions __a = n_layer __a = n_head __a = n_inner __a = activation_function __a = resid_pdrop __a = embd_pdrop __a = attn_pdrop __a = layer_norm_epsilon __a = initializer_range __a = scale_attn_weights __a = use_cache __a = scale_attn_by_inverse_layer_idx __a = reorder_and_upcast_attn __a = bos_token_id __a = eos_token_id super().__init__(bos_token_id=_a , eos_token_id=_a , **_a )
368
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
11
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_layoutlmv2": ["LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv2Config"], "processing_layoutlmv2": ["LayoutLMv2Processor"], "tokenization_layoutlmv2": ["LayoutLMv2Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["LayoutLMv2TokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["LayoutLMv2FeatureExtractor"] lowercase_ = ["LayoutLMv2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv2ForQuestionAnswering", "LayoutLMv2ForSequenceClassification", "LayoutLMv2ForTokenClassification", "LayoutLMv2Layer", "LayoutLMv2Model", "LayoutLMv2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
369
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
0
def lowercase ( lowerCAmelCase__ : Optional[int] = 100 ) -> int: __a = 0 __a = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(F'''{solution() = }''')
370
"""simple docstring""" from math import factorial, radians def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 18 , lowerCAmelCase__ : int = 10 ) -> float: __a = angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians __a = radians(lowerCAmelCase__ ) __a = angle_in_radians __a = 3 __a = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) __a = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__("doctest").testmod()
11
0
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase ( __lowerCamelCase ): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=False , _a=True , _a="None" , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = relative_attention __a = position_biased_input __a = pos_att_type __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , _a ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = DebertaVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase )[0] __a = model(__lowercase , token_type_ids=__lowercase )[0] __a = model(__lowercase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = DebertaVaForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = DebertaVaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowercase ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = DebertaVaForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = DebertaVaForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = DebertaVaForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( __a ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) __UpperCAmelCase : Dict = ( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[str] = False __UpperCAmelCase : Dict = False __UpperCAmelCase : str = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = DebertaVaModelTester(self ) __a = ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowercase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowercase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowercase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowercase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowercase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowercase ) @slow def __UpperCAmelCase ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = DebertaVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='''Model not available yet''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): __a = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) __a = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) __a = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a = model(__lowercase , attention_mask=__lowercase )[0] # compare the actual values for a slice. __a = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowercase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
371
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : dict ) -> tuple: return (data["data"], data["target"]) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ) -> np.ndarray: __a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowerCAmelCase__ , lowerCAmelCase__ ) # Predict target for test data __a = xgb.predict(lowerCAmelCase__ ) __a = predictions.reshape(len(lowerCAmelCase__ ) , 1 ) return predictions def lowercase ( ) -> None: __a = fetch_california_housing() __a , __a = data_handling(lowerCAmelCase__ ) __a , __a , __a , __a = train_test_split( lowerCAmelCase__ , lowerCAmelCase__ , test_size=0.25 , random_state=1 ) __a = xgboost(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
11
0
"""simple docstring""" import math import os import sys def lowercase ( lowerCAmelCase__ : Dict ) -> str: __a = '' try: with open(_UpperCAmelCase , '''rb''' ) as binary_file: __a = binary_file.read() for dat in data: __a = f'''{dat:08b}''' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] ) -> None: lexicon.pop(_UpperCAmelCase ) __a = last_match_id if math.loga(_UpperCAmelCase ).is_integer(): for curr_key in lexicon: __a = '0' + lexicon[curr_key] __a = bin(_UpperCAmelCase )[2:] def lowercase ( lowerCAmelCase__ : Dict ) -> str: __a = {'0': '0', '1': '1'} __a = '', '' __a = len(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __a = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) index += 1 __a = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __a = lexicon[curr_string] result += last_match_id return result def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any] ) -> str: __a = os.path.getsize(_UpperCAmelCase ) __a = bin(_UpperCAmelCase )[2:] __a = len(_UpperCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> None: __a = 8 try: with open(_UpperCAmelCase , '''wb''' ) as opened_file: __a = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase ) , _UpperCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any ) -> None: __a = read_file_binary(_UpperCAmelCase ) __a = compress_data(_UpperCAmelCase ) __a = add_file_length(_UpperCAmelCase , _UpperCAmelCase ) write_file_binary(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) __lowerCAmelCase = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) __lowerCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) __lowerCAmelCase = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) __lowerCAmelCase = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) __lowerCAmelCase = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) __lowerCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = FLAX_MODEL_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModel) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : List[str] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : str = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : int = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Optional[int] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : Any = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING __lowerCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class __lowerCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __UpperCAmelCase : List[str] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING __lowerCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
351
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'funnel' __UpperCAmelCase : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', } def __init__( self , _a=30_522 , _a=[4, 4, 4] , _a=None , _a=2 , _a=768 , _a=12 , _a=64 , _a=3_072 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=None , _a=1E-9 , _a="mean" , _a="relative_shift" , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = block_sizes __a = [1] * len(_a ) if block_repeats is None else block_repeats assert len(_a ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __a = num_decoder_layers __a = d_model __a = n_head __a = d_head __a = d_inner __a = hidden_act __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = initializer_range __a = initializer_std __a = layer_norm_eps assert pooling_type in [ "mean", "max", ], f'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' __a = pooling_type assert attention_type in [ "relative_shift", "factorized", ], f'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' __a = attention_type __a = separate_cls __a = truncate_seq __a = pool_q_only super().__init__(**_a ) @property def __UpperCAmelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.''' ) @property def __UpperCAmelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError('''This model does not support the setting of `num_blocks`. Please set `block_sizes`.''' )
11
0
"""simple docstring""" import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=False , _a=True , _a=99 , _a=64 , _a=5 , _a=4 , _a=64 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): return MPNetConfig.from_pretrained('''microsoft/mpnet-base''' ) def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MPNetConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = MPNetModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , _a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = MPNetForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MPNetForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MPNetForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MPNetForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a)) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) __UpperCAmelCase : Optional[int] = ( { 'feature-extraction': MPNetModel, 'fill-mask': MPNetForMaskedLM, 'question-answering': MPNetForQuestionAnswering, 'text-classification': MPNetForSequenceClassification, 'token-classification': MPNetForTokenClassification, 'zero-shot': MPNetForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Optional[int] = True def __UpperCAmelCase ( self ): __a = MPNetModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*_a ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MPNetModel.from_pretrained('''microsoft/mpnet-base''' ) __a = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) __a = model(_a )[0] __a = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
352
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> str: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _a ) __a = image_processor.post_process_semantic_segmentation(outputs=_a ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _a )
11
0
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } lowercase_ = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } lowercase_ = { "facebook/blenderbot_small-90M": 5_1_2, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = BlenderbotSmallTokenizer def __init__( self , _a=None , _a=None , _a="<|endoftext|>" , _a="<|endoftext|>" , _a="<|endoftext|>" , _a=False , _a=True , **_a , ): super().__init__( ByteLevelBPETokenizer( vocab=_lowerCAmelCase , merges=_lowerCAmelCase , add_prefix_space=_lowerCAmelCase , trim_offsets=_lowerCAmelCase , ) , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , unk_token=_lowerCAmelCase , **_lowerCAmelCase , ) __a = add_prefix_space def __UpperCAmelCase ( self , _a , _a=None ): __a = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
353
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
11
0
"""simple docstring""" from __future__ import annotations import typing from collections.abc import Iterable import numpy as np lowercase_ = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 lowercase_ = typing.Union[np.floataa, int, float] # noqa: UP007 def lowercase ( lowerCAmelCase__ : Vector , lowerCAmelCase__ : Vector ) -> VectorOut: return np.sqrt(np.sum((np.asarray(_A ) - np.asarray(_A )) ** 2 ) ) def lowercase ( lowerCAmelCase__ : Vector , lowerCAmelCase__ : Vector ) -> VectorOut: return sum((va - va) ** 2 for va, va in zip(_A , _A ) ) ** (1 / 2) if __name__ == "__main__": def lowercase ( ) -> None: from timeit import timeit print('''Without Numpy''' ) print( timeit( '''euclidean_distance_no_np([1, 2, 3], [4, 5, 6])''' , number=10000 , globals=globals() , ) ) print('''With Numpy''' ) print( timeit( '''euclidean_distance([1, 2, 3], [4, 5, 6])''' , number=10000 , globals=globals() , ) ) benchmark()
354
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __UpperCAmelCase ( self , _a , _a=None , _a="This is a sound of {}." ): if isinstance(_a , _a ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(_a ).content else: with open(_a , '''rb''' ) as f: __a = f.read() if isinstance(_a , _a ): __a = ffmpeg_read(_a , self.feature_extractor.sampling_rate ) if not isinstance(_a , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) __a = candidate_labels __a = [hypothesis_template.format(_a ) for x in candidate_labels] __a = self.tokenizer(_a , return_tensors=self.framework , padding=_a ) __a = [text_inputs] return inputs def __UpperCAmelCase ( self , _a ): __a = model_inputs.pop('''candidate_labels''' ) __a = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _a ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**_a , **_a ) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.pop('''candidate_labels''' ) __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_a , _a ) , key=lambda _a : -x[0] ) ] return result
11
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( snake_case_ ): '''simple docstring''' def __init__( self , *_a , **_a ): warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
355
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
11
0
"""simple docstring""" import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() gc.collect() def __UpperCAmelCase ( self ): __a = FlaxControlNetModel.from_pretrained( '''lllyasviel/sd-controlnet-canny''' , from_pt=lowerCamelCase__ , dtype=jnp.bfloataa ) __a = FlaxStableDiffusionControlNetPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , controlnet=lowerCamelCase__ , from_pt=lowerCamelCase__ , dtype=jnp.bfloataa ) __a = controlnet_params __a = '''bird''' __a = jax.device_count() __a = pipe.prepare_text_inputs([prompts] * num_samples ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''' ) __a = pipe.prepare_image_inputs([canny_image] * num_samples ) __a = jax.random.PRNGKey(0 ) __a = jax.random.split(lowerCamelCase__ , jax.device_count() ) __a = replicate(lowerCamelCase__ ) __a = shard(lowerCamelCase__ ) __a = shard(lowerCamelCase__ ) __a = pipe( prompt_ids=lowerCamelCase__ , image=lowerCamelCase__ , params=lowerCamelCase__ , prng_seed=lowerCamelCase__ , num_inference_steps=50 , jit=lowerCamelCase__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __a = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __a = images[0, 253:256, 253:256, -1] __a = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __a = jnp.array( [0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): __a = FlaxControlNetModel.from_pretrained( '''lllyasviel/sd-controlnet-openpose''' , from_pt=lowerCamelCase__ , dtype=jnp.bfloataa ) __a = FlaxStableDiffusionControlNetPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , controlnet=lowerCamelCase__ , from_pt=lowerCamelCase__ , dtype=jnp.bfloataa ) __a = controlnet_params __a = '''Chef in the kitchen''' __a = jax.device_count() __a = pipe.prepare_text_inputs([prompts] * num_samples ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png''' ) __a = pipe.prepare_image_inputs([pose_image] * num_samples ) __a = jax.random.PRNGKey(0 ) __a = jax.random.split(lowerCamelCase__ , jax.device_count() ) __a = replicate(lowerCamelCase__ ) __a = shard(lowerCamelCase__ ) __a = shard(lowerCamelCase__ ) __a = pipe( prompt_ids=lowerCamelCase__ , image=lowerCamelCase__ , params=lowerCamelCase__ , prng_seed=lowerCamelCase__ , num_inference_steps=50 , jit=lowerCamelCase__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __a = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __a = images[0, 253:256, 253:256, -1] __a = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __a = jnp.array( [[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
356
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" import warnings warnings.warn( "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " "`from accelerate import find_executable_batch_size` to avoid this warning.", FutureWarning, )
357
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): self.assertEqual(len(_a ) , len(_a ) ) for a, b in zip(_a , _a ): self.assertAlmostEqual(_a , _a , delta=_a ) def __UpperCAmelCase ( self ): __a = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_a ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def __UpperCAmelCase ( self ): __a = None ops.enable_eager_execution_internal() __a = tf.config.list_physical_devices('''CPU''' ) if len(_a ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a = tf.config.list_logical_devices(device_type='''CPU''' ) __a = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a = GradientAccumulator() __a = tf.Variable([4.0, 3.0] ) __a , __a = create_optimizer(5E-5 , 10 , 5 ) __a = tf.Variable([0.0, 0.0] , trainable=_a ) def accumulate_on_replica(_a ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_a , _a ): with strategy.scope(): __a = strategy.experimental_local_results(_a ) local_variables[0].assign(_a ) local_variables[1].assign(_a ) strategy.run(_a , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_a ) def _check_local_values(_a , _a ): __a = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _a , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _a , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
11
0
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE__ ) class __lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) requires_backends(self , '''vision''' ) requires_backends(self , '''torch''' ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) self.check_model_type(_a ) def __UpperCAmelCase ( self , **_a ): __a = {} __a = {} __a = {} # preprocess args if "points_per_batch" in kwargs: __a = kwargs['points_per_batch'] if "points_per_crop" in kwargs: __a = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: __a = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: __a = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: __a = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: __a = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: __a = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: __a = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: __a = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: __a = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: __a = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: __a = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , _a , *_a , _a=None , _a=None , **_a ): return super().__call__(_a , *_a , num_workers=_a , batch_size=_a , **_a ) def __UpperCAmelCase ( self , _a , _a=64 , _a = 0 , _a = 512 / 1_500 , _a = 32 , _a = 1 , ): __a = load_image(_a ) __a = self.image_processor.size['longest_edge'] __a = self.image_processor.generate_crop_boxes( _a , _a , _a , _a , _a , _a ) __a = self.image_processor(images=_a , return_tensors='''pt''' ) with self.device_placement(): if self.framework == "pt": __a = self.get_inference_context() with inference_context(): __a = self._ensure_tensor_on_device(_a , device=self.device ) __a = self.model.get_image_embeddings(model_inputs.pop('''pixel_values''' ) ) __a = image_embeddings __a = grid_points.shape[1] __a = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ''' '''To return all points at once, set points_per_batch to None''' ) for i in range(0 , _a , _a ): __a = grid_points[:, i : i + points_per_batch, :, :] __a = input_labels[:, i : i + points_per_batch] __a = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def __UpperCAmelCase ( self , _a , _a=0.88 , _a=0.95 , _a=0 , _a=1 , ): __a = model_inputs.pop('''input_boxes''' ) __a = model_inputs.pop('''is_last''' ) __a = model_inputs.pop('''original_sizes''' ).tolist() __a = model_inputs.pop('''reshaped_input_sizes''' ).tolist() __a = self.model(**_a ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __a = model_outputs['pred_masks'] __a = self.image_processor.post_process_masks( _a , _a , _a , _a , binarize=_a ) __a = model_outputs['iou_scores'] __a = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , _a , _a , _a , _a , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def __UpperCAmelCase ( self , _a , _a=False , _a=False , _a=0.7 , ): __a = [] __a = [] __a = [] for model_output in model_outputs: all_scores.append(model_output.pop('''iou_scores''' ) ) all_masks.extend(model_output.pop('''masks''' ) ) all_boxes.append(model_output.pop('''boxes''' ) ) __a = torch.cat(_a ) __a = torch.cat(_a ) __a = self.image_processor.post_process_for_mask_generation( _a , _a , _a , _a ) __a = defaultdict(_a ) for output in model_outputs: for k, v in output.items(): extra[k].append(_a ) __a = {} if output_rle_mask: __a = rle_mask if output_bboxes_mask: __a = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
358
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: lowercase_ = None lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json", "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json", }, } lowercase_ = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off lowercase_ = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = ['input_ids', 'attention_mask'] __UpperCAmelCase : Optional[Any] = MBartTokenizer __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , **_a , ) __a = vocab_file __a = False if not self.vocab_file else True __a = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __a = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __a = src_lang if src_lang is not None else '''en_XX''' __a = self.convert_tokens_to_ids(self._src_lang ) __a = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __UpperCAmelCase ( self ): return self._src_lang @src_lang.setter def __UpperCAmelCase ( self , _a ): __a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a , _a , _a , **_a ): if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __a = src_lang __a = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) __a = self.convert_tokens_to_ids(_a ) __a = tgt_lang_id return inputs def __UpperCAmelCase ( self , _a , _a = "en_XX" , _a = None , _a = "ro_RO" , **_a , ): __a = src_lang __a = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def __UpperCAmelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __UpperCAmelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a , _a = None ): 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(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return __a = 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 ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
11
0
"""simple docstring""" import sys def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Any: __a = len(a__ ) __a = [[0 for x in range(a__ )] for x in range(a__ )] __a = [[0 for x in range(a__ )] for x in range(a__ )] for chain_length in range(2 , a__ ): for a in range(1 , n - chain_length + 1 ): __a = a + chain_length - 1 __a = sys.maxsize for c in range(a__ , a__ ): __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 lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : int ) -> Union[str, Any]: if i == j: print('''A''' + str(a__ ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(a__ , a__ , optimal_solution[i][j] ) print_optiomal_solution(a__ , optimal_solution[i][j] + 1 , a__ ) print(''')''' , end=''' ''' ) def lowercase ( ) -> Dict: __a = [30, 35, 15, 5, 10, 20, 25] __a = len(a__ ) # 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(a__ ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(a__ , 1 , n - 1 ) if __name__ == "__main__": main()
359
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging 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.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn 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]\n" class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-question-answering''' ) self.tool.setup() __a = load_tool('''text-question-answering''' , remote=_a ) def __UpperCAmelCase ( self ): __a = self.tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' )
11
0
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __lowercase ): '''simple docstring''' __UpperCAmelCase : Any = (KDPMaDiscreteScheduler,) __UpperCAmelCase : Dict = 1_0 def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**UpperCAmelCase__ ) return config def __UpperCAmelCase ( self ): for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__ ) def __UpperCAmelCase ( self ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=UpperCAmelCase__ , beta_end=UpperCAmelCase__ ) def __UpperCAmelCase ( self ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=UpperCAmelCase__ ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__ ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(prediction_type='''v_prediction''' ) __a = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma __a = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __a = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) __a = model(UpperCAmelCase__ , UpperCAmelCase__ ) __a = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __a = output.prev_sample __a = torch.sum(torch.abs(UpperCAmelCase__ ) ) __a = torch.mean(torch.abs(UpperCAmelCase__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1_112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_428_650_170_972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0002 ) < 1E-3 def __UpperCAmelCase ( self ): if torch_device == "mps": return __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma __a = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __a = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) __a = model(UpperCAmelCase__ , UpperCAmelCase__ ) __a = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __a = output.prev_sample __a = torch.sum(torch.abs(UpperCAmelCase__ ) ) __a = torch.mean(torch.abs(UpperCAmelCase__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4125 ) < 1E-2 assert abs(result_mean.item() - 0.0266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1E-2 assert abs(result_mean.item() - 0.0266 ) < 1E-3 def __UpperCAmelCase ( self ): if torch_device == "mps": return __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps , device=UpperCAmelCase__ ) __a = self.dummy_model() __a = self.dummy_sample_deter.to(UpperCAmelCase__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: __a = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) __a = model(UpperCAmelCase__ , UpperCAmelCase__ ) __a = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __a = output.prev_sample __a = torch.sum(torch.abs(UpperCAmelCase__ ) ) __a = torch.mean(torch.abs(UpperCAmelCase__ ) ) if str(UpperCAmelCase__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4125 ) < 1E-2 assert abs(result_mean.item() - 0.0266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1E-2 assert abs(result_mean.item() - 0.0266 ) < 1E-3
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig", ], "processing_blip_2": ["Blip2Processor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Blip2Model", "Blip2QFormerModel", "Blip2PreTrainedModel", "Blip2ForConditionalGeneration", "Blip2VisionModel", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" from math import loga def lowercase ( lowerCAmelCase__ : Tuple ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
361
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a = len(lowerCAmelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCAmelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCAmelCase__ , lowerCAmelCase__ , ) def lowercase ( lowerCAmelCase__ : int ) -> None: __a = [] depth_first_search([] , [] , [] , lowerCAmelCase__ , lowerCAmelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCAmelCase__ ) print('''''' ) print(len(lowerCAmelCase__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
11
0
"""simple docstring""" import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse("0.8.3"): raise Exception("requires gluonnlp == 0.8.3") if version.parse(mx.__version__) != version.parse("1.5.0"): raise Exception("requires mxnet == 1.5.0") logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = 'The Nymphenburg Palace is a beautiful palace in Munich!' def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] ) -> Optional[int]: __a = { '''attention_cell''': '''multi_head''', '''num_layers''': 4, '''units''': 1024, '''hidden_size''': 768, '''max_length''': 512, '''num_heads''': 8, '''scaled''': True, '''dropout''': 0.1, '''use_residual''': True, '''embed_size''': 1024, '''embed_dropout''': 0.1, '''word_embed''': None, '''layer_norm_eps''': 1e-5, '''token_type_vocab_size''': 2, } __a = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a = BERTEncoder( attention_cell=predefined_args['''attention_cell'''] , num_layers=predefined_args['''num_layers'''] , units=predefined_args['''units'''] , hidden_size=predefined_args['''hidden_size'''] , max_length=predefined_args['''max_length'''] , num_heads=predefined_args['''num_heads'''] , scaled=predefined_args['''scaled'''] , dropout=predefined_args['''dropout'''] , output_attention=lowercase__ , output_all_encodings=lowercase__ , use_residual=predefined_args['''use_residual'''] , activation=predefined_args.get('''activation''' , '''gelu''' ) , layer_norm_eps=predefined_args.get('''layer_norm_eps''' , lowercase__ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a = '''openwebtext_ccnews_stories_books_cased''' # Specify download folder to Gluonnlp's vocab __a = os.path.join(get_home_dir() , '''models''' ) __a = _load_vocab(lowercase__ , lowercase__ , lowercase__ , cls=lowercase__ ) __a = nlp.model.BERTModel( lowercase__ , len(lowercase__ ) , units=predefined_args['''units'''] , embed_size=predefined_args['''embed_size'''] , embed_dropout=predefined_args['''embed_dropout'''] , word_embed=predefined_args['''word_embed'''] , use_pooler=lowercase__ , use_token_type_embed=lowercase__ , token_type_vocab_size=predefined_args['''token_type_vocab_size'''] , use_classifier=lowercase__ , use_decoder=lowercase__ , ) original_bort.load_parameters(lowercase__ , cast_dtype=lowercase__ , ignore_extra=lowercase__ ) __a = original_bort._collect_params_with_prefix() # Build our config 🤗 __a = { '''architectures''': ['''BertForMaskedLM'''], '''attention_probs_dropout_prob''': predefined_args['''dropout'''], '''hidden_act''': '''gelu''', '''hidden_dropout_prob''': predefined_args['''dropout'''], '''hidden_size''': predefined_args['''embed_size'''], '''initializer_range''': 0.02, '''intermediate_size''': predefined_args['''hidden_size'''], '''layer_norm_eps''': predefined_args['''layer_norm_eps'''], '''max_position_embeddings''': predefined_args['''max_length'''], '''model_type''': '''bort''', '''num_attention_heads''': predefined_args['''num_heads'''], '''num_hidden_layers''': predefined_args['''num_layers'''], '''pad_token_id''': 1, # 2 = BERT, 1 = RoBERTa '''type_vocab_size''': 1, # 2 = BERT, 1 = RoBERTa '''vocab_size''': len(lowercase__ ), } __a = BertConfig.from_dict(lowercase__ ) __a = BertForMaskedLM(lowercase__ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCAmelCase__ : str ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Any ): __a = hf_param.shape __a = to_torch(params[gluon_param] ) __a = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , '''word_embed.0.weight''' ) __a = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , '''encoder.position_weight''' ) __a = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , '''encoder.layer_norm.beta''' ) __a = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , '''encoder.layer_norm.gamma''' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a = hf_bort_model.bert.encoder.layer[i] # self attention __a = layer.attention.self __a = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a = layer.attention.output __a = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a = layer.intermediate __a = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a = layer.output __a = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a = RobertaTokenizer.from_pretrained('''roberta-base''' ) __a = tokenizer.encode_plus(lowercase__ )['''input_ids'''] # Get gluon output __a = mx.nd.array([input_ids] ) __a = original_bort(inputs=lowercase__ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowercase__ ) __a = BertModel.from_pretrained(lowercase__ ) hf_bort_model.eval() __a = tokenizer.encode_plus(lowercase__ , return_tensors='''pt''' ) __a = hf_bort_model(**lowercase__ )[0] __a = output_gluon[0].asnumpy() __a = output_hf[0].detach().numpy() __a = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a = np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) if success: print('''✔️ Both model do output the same tensors''' ) else: print('''❌ Both model do **NOT** output the same tensors''' ) print('''Absolute difference is:''' , lowercase__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--bort_checkpoint_path", default=None, type=str, required=True, help="Path the official Bort params file." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowercase_ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
362
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
11
0
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowercase ( lowerCAmelCase__ : Optional[int] ) -> Optional[Any]: __a = fname.split(os.path.sep )[-1] return re.search(r'''^(.*)_\d+\.jpg$''' , __snake_case ).groups()[0] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a=None , _a=None ): __a = file_names __a = image_transform __a = label_to_id def __len__( self ): return len(self.file_names ) def __getitem__( self , _a ): __a = self.file_names[idx] __a = PIL.Image.open(_SCREAMING_SNAKE_CASE ) __a = raw_image.convert('''RGB''' ) if self.image_transform is not None: __a = self.image_transform(_SCREAMING_SNAKE_CASE ) __a = extract_label(_SCREAMING_SNAKE_CASE ) if self.label_to_id is not None: __a = self.label_to_id[label] return {"image": image, "label": label} def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: # Initialize accelerator if args.with_tracking: __a = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: __a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config["lr"] __a = int(config['''num_epochs'''] ) __a = int(config['''seed'''] ) __a = int(config['''batch_size'''] ) __a = config["image_size"] if not isinstance(__snake_case , (list, tuple) ): __a = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , '''isdigit''' ): if args.checkpointing_steps == "epoch": __a = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): __a = int(args.checkpointing_steps ) else: raise ValueError( f'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' ) else: __a = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: __a = os.path.split(__snake_case )[-1].split('''.''' )[0] accelerator.init_trackers(__snake_case , __snake_case ) # Grab all the image filenames __a = [os.path.join(args.data_dir , __snake_case ) for fname in os.listdir(args.data_dir ) if fname.endswith('''.jpg''' )] # Build the label correspondences __a = [extract_label(__snake_case ) for fname in file_names] __a = list(set(__snake_case ) ) id_to_label.sort() __a = {lbl: i for i, lbl in enumerate(__snake_case )} # Set the seed before splitting the data. np.random.seed(__snake_case ) torch.manual_seed(__snake_case ) torch.cuda.manual_seed_all(__snake_case ) # Split our filenames between train and validation __a = np.random.permutation(len(__snake_case ) ) __a = int(0.8 * len(__snake_case ) ) __a = random_perm[:cut] __a = random_perm[cut:] # For training we use a simple RandomResizedCrop __a = Compose([RandomResizedCrop(__snake_case , scale=(0.5, 1.0) ), ToTensor()] ) __a = PetsDataset( [file_names[i] for i in train_split] , image_transform=__snake_case , label_to_id=__snake_case ) # For evaluation, we use a deterministic Resize __a = Compose([Resize(__snake_case ), ToTensor()] ) __a = PetsDataset([file_names[i] for i in eval_split] , image_transform=__snake_case , label_to_id=__snake_case ) # Instantiate dataloaders. __a = DataLoader(__snake_case , shuffle=__snake_case , batch_size=__snake_case , num_workers=4 ) __a = DataLoader(__snake_case , shuffle=__snake_case , batch_size=__snake_case , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = create_model('''resnet50d''' , pretrained=__snake_case , num_classes=len(__snake_case ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __a = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): __a = False for param in model.get_classifier().parameters(): __a = True # We normalize the batches of images to be a bit faster. __a = torch.tensor(model.default_cfg['''mean'''] )[None, :, None, None].to(accelerator.device ) __a = torch.tensor(model.default_cfg['''std'''] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer __a = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler __a = OneCycleLR(optimizer=__snake_case , max_lr=__snake_case , epochs=__snake_case , steps_per_epoch=len(__snake_case ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a = accelerator.prepare( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) # We need to keep track of how many total steps we have iterated over __a = 0 # We also need to keep track of the starting epoch so files are named properly __a = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(f'''Resumed from checkpoint: {args.resume_from_checkpoint}''' ) accelerator.load_state(args.resume_from_checkpoint ) __a = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint __a = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) __a = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` __a = os.path.splitext(__snake_case )[0] if "epoch" in training_difference: __a = int(training_difference.replace('''epoch_''' , '''''' ) ) + 1 __a = None else: __a = int(training_difference.replace('''step_''' , '''''' ) ) __a = resume_step // len(__snake_case ) resume_step -= starting_epoch * len(__snake_case ) # Now we train the model for epoch in range(__snake_case , __snake_case ): model.train() if args.with_tracking: __a = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step __a = accelerator.skip_first_batches(__snake_case , __snake_case ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader __a = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. __a = {k: v.to(accelerator.device ) for k, v in batch.items()} __a = (batch["image"] - mean) / std __a = model(__snake_case ) __a = torch.nn.functional.cross_entropy(__snake_case , batch['''label'''] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__snake_case , __snake_case ): __a = f'''step_{overall_step}''' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: __a = os.path.join(args.output_dir , __snake_case ) accelerator.save_state(__snake_case ) model.eval() __a = 0 __a = 0 for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. __a = {k: v.to(accelerator.device ) for k, v in batch.items()} __a = (batch["image"] - mean) / std with torch.no_grad(): __a = model(__snake_case ) __a = outputs.argmax(dim=-1 ) __a = accelerator.gather_for_metrics((predictions, batch['''label''']) ) __a = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() __a = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}: {100 * eval_metric:.2f}''' ) if args.with_tracking: accelerator.log( { '''accuracy''': 100 * eval_metric, '''train_loss''': total_loss.item() / len(__snake_case ), '''epoch''': epoch, } , step=__snake_case , ) if checkpointing_steps == "epoch": __a = f'''epoch_{epoch}''' if args.output_dir is not None: __a = os.path.join(args.output_dir , __snake_case ) accelerator.save_state(__snake_case ) if args.with_tracking: accelerator.end_training() def lowercase ( ) -> Tuple: __a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument('''--data_dir''' , required=__snake_case , help='''The data folder on disk.''' ) parser.add_argument('''--fp16''' , action='''store_true''' , help='''If passed, will use FP16 training.''' ) parser.add_argument( '''--mixed_precision''' , type=__snake_case , default=__snake_case , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--checkpointing_steps''' , type=__snake_case , default=__snake_case , help='''Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.''' , ) parser.add_argument( '''--output_dir''' , type=__snake_case , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=__snake_case , default=__snake_case , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=__snake_case , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) __a = parser.parse_args() __a = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} training_function(__snake_case , __snake_case ) if __name__ == "__main__": main()
363
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = 'vit_mae' def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=True , _a=16 , _a=512 , _a=8 , _a=2_048 , _a=0.75 , _a=False , **_a , ): super().__init__(**_a ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = decoder_num_attention_heads __a = decoder_hidden_size __a = decoder_num_hidden_layers __a = decoder_intermediate_size __a = mask_ratio __a = norm_pix_loss
11
0
"""simple docstring""" import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : Dict = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] ) __UpperCAmelCase : List[str] = ["accelerate", "launch"] __UpperCAmelCase : List[Any] = Path.home() / ".cache/huggingface/accelerate" __UpperCAmelCase : Tuple = "default_config.yaml" __UpperCAmelCase : Tuple = config_folder / config_file __UpperCAmelCase : int = config_folder / "_default_config.yaml" __UpperCAmelCase : Optional[Any] = Path('tests/test_configs' ) @classmethod def __UpperCAmelCase ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __UpperCAmelCase ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __UpperCAmelCase ( self ): __a = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def __UpperCAmelCase ( self ): for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=lowerCamelCase_ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(lowerCamelCase_ ), self.test_file_path] , env=os.environ.copy() ) def __UpperCAmelCase ( self ): execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = "test-tpu" __UpperCAmelCase : Optional[int] = "us-central1-a" __UpperCAmelCase : Dict = "ls" __UpperCAmelCase : Optional[int] = ["accelerate", "tpu-config"] __UpperCAmelCase : Optional[Any] = "cd /usr/share" __UpperCAmelCase : Optional[Any] = "tests/test_samples/test_command_file.sh" __UpperCAmelCase : int = "Running gcloud compute tpus tpu-vm ssh" def __UpperCAmelCase ( self ): __a = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=lowerCamelCase_ ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo \"Hello World\"''', '''--debug''', ] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , lowerCamelCase_ , ) def __UpperCAmelCase ( self ): __a = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=lowerCamelCase_ , ) self.assertIn( f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , lowerCamelCase_ , )
364
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Optional[int] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
11
0
"""simple docstring""" from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split lowercase_ = datasets.load_iris() lowercase_ = np.array(data["data"]) lowercase_ = np.array(data["target"]) lowercase_ = data["""target_names"""] lowercase_ = train_test_split(X, y) def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> Union[str, Any]: return np.linalg.norm(np.array(SCREAMING_SNAKE_CASE_ ) - np.array(SCREAMING_SNAKE_CASE_ ) ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int]=5 ) -> Tuple: __a = zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # List of distances of all points from the point to be classified __a = [] for data_point in data: __a = euclidean_distance(data_point[0] , SCREAMING_SNAKE_CASE_ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __a = [i[1] for i in sorted(SCREAMING_SNAKE_CASE_ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __a = Counter(SCREAMING_SNAKE_CASE_ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
365
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
11
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class __lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' __UpperCAmelCase : Dict = """pix2struct_text_model""" __UpperCAmelCase : str = ["""past_key_values"""] __UpperCAmelCase : Dict = { """hidden_size""": """hidden_size""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , _a=50_244 , _a=768 , _a=64 , _a=2_048 , _a=12 , _a=12 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="gelu_new" , _a=0 , _a=False , _a=0 , _a=1 , _a=False , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = d_kv __a = d_ff __a = num_layers __a = num_heads __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = dropout_rate __a = layer_norm_epsilon __a = initializer_factor __a = use_cache __a = eos_token_id __a = decoder_start_token_id # for backwards compatibility __a = dense_act_fn super().__init__( pad_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , decoder_start_token_id=_UpperCAmelCase , tie_word_embeddings=_UpperCAmelCase , is_decoder=_UpperCAmelCase , **_UpperCAmelCase , ) @classmethod def __UpperCAmelCase ( cls , _a , **_a ): cls._set_token_in_kwargs(_UpperCAmelCase ) __a , __a = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": __a = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class __lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' __UpperCAmelCase : Optional[int] = """pix2struct_vision_model""" def __init__( self , _a=768 , _a=768 , _a=2_048 , _a=64 , _a=12 , _a=12 , _a="gelu_new" , _a=1E-6 , _a=0.0 , _a=0.0 , _a=1E-10 , _a=1.0 , _a=4_096 , _a=32 , _a=128 , **_a , ): super().__init__(**_UpperCAmelCase ) __a = hidden_size __a = patch_embed_hidden_size __a = d_ff __a = dropout_rate __a = num_hidden_layers __a = num_attention_heads __a = initializer_range __a = initializer_factor __a = attention_dropout __a = layer_norm_eps __a = dense_act_fn __a = seq_len __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = d_kv @classmethod def __UpperCAmelCase ( cls , _a , **_a ): cls._set_token_in_kwargs(_UpperCAmelCase ) __a , __a = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": __a = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class __lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' __UpperCAmelCase : str = """pix2struct""" __UpperCAmelCase : Union[str, Any] = True def __init__( self , _a=None , _a=None , _a=1.0 , _a=0.02 , _a=False , _a=False , _a=True , **_a , ): super().__init__(tie_word_embeddings=_UpperCAmelCase , is_encoder_decoder=_UpperCAmelCase , **_UpperCAmelCase ) if text_config is None: __a = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: __a = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) __a = PixaStructTextConfig(**_UpperCAmelCase ) __a = PixaStructVisionConfig(**_UpperCAmelCase ) __a = self.text_config.decoder_start_token_id __a = self.text_config.pad_token_id __a = self.text_config.eos_token_id __a = initializer_factor __a = initializer_range __a = self.initializer_range __a = self.initializer_range __a = is_vqa @classmethod def __UpperCAmelCase ( cls , _a , _a , **_a ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_UpperCAmelCase ) def __UpperCAmelCase ( self ): __a = copy.deepcopy(self.__dict__ ) __a = self.text_config.to_dict() __a = self.vision_config.to_dict() __a = self.__class__.model_type return output
366
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'rwkv' __UpperCAmelCase : Optional[Any] = {'max_position_embeddings': 'context_length'} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): __a = vocab_size __a = context_length __a = hidden_size __a = num_hidden_layers __a = attention_hidden_size if attention_hidden_size is not None else hidden_size __a = intermediate_size if intermediate_size is not None else 4 * hidden_size __a = layer_norm_epsilon __a = rescale_every __a = use_cache __a = bos_token_id __a = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
11
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', '''JukeboxPriorConfig''', '''JukeboxVQVAEConfig''', ], '''tokenization_jukebox''': ['''JukeboxTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''JukeboxModel''', '''JukeboxPreTrainedModel''', '''JukeboxVQVAE''', '''JukeboxPrior''', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
367
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = (UnCLIPScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCAmelCase ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_a , prev_timestep=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''fixed_small_log''' ) __a = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''learned_range''' ) __a = scheduler_class(**_a ) __a = 0.5 assert scheduler._get_variance(1 , predicted_variance=_a ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_a ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_a ) - -0.001_0011 < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(25 ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) if i + 1 == timesteps.shape[0]: __a = None else: __a = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a = scheduler.step( _a , _a , _a , prev_timestep=_a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass
11
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["OwlViTFeatureExtractor"] lowercase_ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
368
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
11
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int = 1000 ) -> int: __a = -1 __a = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c __a = (n * n - 2 * a * n) // (2 * n - 2 * a) __a = n - a - b if c * c == (a * a + b * b): __a = a * b * c if candidate >= product: __a = candidate return product if __name__ == "__main__": print(F'''{solution() = }''')
369
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
0
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort lowercase_ = logging.get_logger(__name__) lowercase_ = { "tensor(bool)": np.bool_, "tensor(int8)": np.inta, "tensor(uint8)": np.uinta, "tensor(int16)": np.intaa, "tensor(uint16)": np.uintaa, "tensor(int32)": np.intaa, "tensor(uint32)": np.uintaa, "tensor(int64)": np.intaa, "tensor(uint64)": np.uintaa, "tensor(float16)": np.floataa, "tensor(float)": np.floataa, "tensor(double)": np.floataa, } class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a=None , **_a ): logger.info('''`diffusers.OnnxRuntimeModel` is experimental and might change in the future.''' ) __a = model __a = kwargs.get('''model_save_dir''' , _SCREAMING_SNAKE_CASE ) __a = kwargs.get('''latest_model_name''' , _SCREAMING_SNAKE_CASE ) def __call__( self , **_a ): __a = {k: np.array(_SCREAMING_SNAKE_CASE ) for k, v in kwargs.items()} return self.model.run(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @staticmethod def __UpperCAmelCase ( _a , _a=None , _a=None ): if provider is None: logger.info('''No onnxruntime provider specified, using CPUExecutionProvider''' ) __a = '''CPUExecutionProvider''' return ort.InferenceSession(_SCREAMING_SNAKE_CASE , providers=[provider] , sess_options=_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self , _a , _a = None , **_a ): __a = file_name if file_name is not None else ONNX_WEIGHTS_NAME __a = self.model_save_dir.joinpath(self.latest_model_name ) __a = Path(_SCREAMING_SNAKE_CASE ).joinpath(_SCREAMING_SNAKE_CASE ) try: shutil.copyfile(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) except shutil.SameFileError: pass # copy external weights (for models >2GB) __a = self.model_save_dir.joinpath(_SCREAMING_SNAKE_CASE ) if src_path.exists(): __a = Path(_SCREAMING_SNAKE_CASE ).joinpath(_SCREAMING_SNAKE_CASE ) try: shutil.copyfile(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) except shutil.SameFileError: pass def __UpperCAmelCase ( self , _a , **_a , ): if os.path.isfile(_SCREAMING_SNAKE_CASE ): logger.error(f'''Provided path ({save_directory}) should be a directory, not a file''' ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) # saving model weights/files self._save_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls , _a , _a = None , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): __a = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_SCREAMING_SNAKE_CASE ): __a = OnnxRuntimeModel.load_model( os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , provider=_SCREAMING_SNAKE_CASE , sess_options=_SCREAMING_SNAKE_CASE ) __a = Path(_SCREAMING_SNAKE_CASE ) # load model from hub else: # download model __a = hf_hub_download( repo_id=_SCREAMING_SNAKE_CASE , filename=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , revision=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , ) __a = Path(_SCREAMING_SNAKE_CASE ).parent __a = Path(_SCREAMING_SNAKE_CASE ).name __a = OnnxRuntimeModel.load_model(_SCREAMING_SNAKE_CASE , provider=_SCREAMING_SNAKE_CASE , sess_options=_SCREAMING_SNAKE_CASE ) return cls(model=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls , _a , _a = True , _a = None , _a = None , **_a , ): __a = None if len(str(_SCREAMING_SNAKE_CASE ).split('''@''' ) ) == 2: __a = model_id.split('''@''' ) return cls._from_pretrained( model_id=_SCREAMING_SNAKE_CASE , revision=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
370
"""simple docstring""" from math import factorial, radians def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 18 , lowerCAmelCase__ : int = 10 ) -> float: __a = angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians __a = radians(lowerCAmelCase__ ) __a = angle_in_radians __a = 3 __a = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) __a = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__("doctest").testmod()
11
0
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> int: __a = MobileBertConfig.from_json_file(lowerCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) __a = MobileBertForPreTraining(lowerCamelCase__ ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowerCamelCase__ ) if __name__ == "__main__": lowercase_ = 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( "--mobilebert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained MobileBERT 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." ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
371
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : dict ) -> tuple: return (data["data"], data["target"]) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ) -> np.ndarray: __a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowerCAmelCase__ , lowerCAmelCase__ ) # Predict target for test data __a = xgb.predict(lowerCAmelCase__ ) __a = predictions.reshape(len(lowerCAmelCase__ ) , 1 ) return predictions def lowercase ( ) -> None: __a = fetch_california_housing() __a , __a = data_handling(lowerCAmelCase__ ) __a , __a , __a , __a = train_test_split( lowerCAmelCase__ , lowerCAmelCase__ , test_size=0.25 , random_state=1 ) __a = xgboost(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
11
0
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy lowercase_ = logging.getLogger(__name__) lowercase_ = "pytorch_model.bin" @dataclasses.dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = dataclasses.field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , ) @dataclasses.dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} ) __UpperCAmelCase : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A csv or a json file containing the validation data.'} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The name of the task to train on.'} , ) __UpperCAmelCase : Optional[List[str]] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The list of labels for the task.'} ) @dataclasses.dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = dataclasses.field( metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default='no' , metadata={ 'help': 'The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]' } , ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=1_0 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) __UpperCAmelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ 'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.' } , ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , ) __UpperCAmelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=1_0_0 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Random seed for initialization.'} , ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: __a = dataset.filter(lambda lowerCAmelCase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 __a = int(eval_result * len(_SCREAMING_SNAKE_CASE ) ) print(_SCREAMING_SNAKE_CASE ) __a = dataset.sort('''probability''' , reverse=_SCREAMING_SNAKE_CASE ) __a = dataset.select(range(_SCREAMING_SNAKE_CASE ) ) __a = dataset.remove_columns(['''label''', '''probability'''] ) __a = dataset.rename_column('''prediction''' , '''label''' ) __a = dataset.map(lambda lowerCAmelCase__ : {"label": idalabel[example["label"]]} ) __a = dataset.shuffle(seed=args.seed ) __a = os.path.join(_SCREAMING_SNAKE_CASE , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(_SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) else: dataset.to_json(_SCREAMING_SNAKE_CASE ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , **lowerCAmelCase__ : Union[str, Any] ) -> str: __a = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() __a = STModelArguments(model_name_or_path=_SCREAMING_SNAKE_CASE ) __a = STDataArguments(train_file=_SCREAMING_SNAKE_CASE , infer_file=_SCREAMING_SNAKE_CASE ) __a = STTrainingArguments(output_dir=_SCREAMING_SNAKE_CASE ) __a = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(_SCREAMING_SNAKE_CASE ).items(): setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for key, value in kwargs.items(): if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Sanity checks __a = {} __a = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None __a = args.train_file __a = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None __a = args.eval_file for key in data_files: __a = data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: __a = extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) __a = f'''{args.output_dir}/self-train_iter-{{}}'''.format __a = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=_SCREAMING_SNAKE_CASE ) os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() __a = None __a = None __a = 0 __a = False # Show the progress bar __a = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): __a = data_dir_format(_SCREAMING_SNAKE_CASE ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 __a = os.path.join(_SCREAMING_SNAKE_CASE , '''stage-1''' ) __a = { "accelerator": accelerator, "model_name_or_path": args.model_name_or_path, "cache_dir": args.cache_dir, "do_train": True, "train_file": data_files["train"] if iteration == 0 else data_files["train_pseudo"], "do_eval": True if args.eval_file is not None else False, "eval_file": data_files["eval"], "do_predict": True, "infer_file": data_files["infer"], "task_name": args.task_name, "label_list": args.label_list, "output_dir": current_output_dir, "eval_metric": args.eval_metric, "evaluation_strategy": args.evaluation_strategy, "early_stopping_patience": args.early_stopping_patience, "early_stopping_threshold": args.early_stopping_threshold, "seed": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): arguments_dict.update({key: value} ) __a = os.path.join(_SCREAMING_SNAKE_CASE , '''best-checkpoint''' , _SCREAMING_SNAKE_CASE ) if os.path.exists(_SCREAMING_SNAKE_CASE ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , _SCREAMING_SNAKE_CASE ) finetune(**_SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() assert os.path.exists(_SCREAMING_SNAKE_CASE ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , _SCREAMING_SNAKE_CASE ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data __a = os.path.join(_SCREAMING_SNAKE_CASE , '''best-checkpoint''' ) __a = os.path.join(_SCREAMING_SNAKE_CASE , '''stage-2''' ) # Update arguments_dict __a = model_path __a = data_files["train"] __a = current_output_dir __a = os.path.join(_SCREAMING_SNAKE_CASE , '''best-checkpoint''' , _SCREAMING_SNAKE_CASE ) if os.path.exists(_SCREAMING_SNAKE_CASE ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , _SCREAMING_SNAKE_CASE ) finetune(**_SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() assert os.path.exists(_SCREAMING_SNAKE_CASE ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , _SCREAMING_SNAKE_CASE ) __a = iteration __a = data_dir_format(iteration + 1 ) __a = AutoConfig.from_pretrained(os.path.join(_SCREAMING_SNAKE_CASE , '''best-checkpoint''' ) ) __a = config.idalabel __a = os.path.join(_SCREAMING_SNAKE_CASE , '''eval_results_best-checkpoint.json''' ) __a = os.path.join(_SCREAMING_SNAKE_CASE , '''test_results_best-checkpoint.json''' ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , '''r''' ) as f: __a = float(json.load(_SCREAMING_SNAKE_CASE )[args.eval_metric] ) __a = os.path.join(_SCREAMING_SNAKE_CASE , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) # Loading the dataset from local csv or json files. __a = load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )["data"] __a = load_dataset('''csv''' , data_files={'''data''': infer_output_file} )["data"] if accelerator.is_main_process: os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) shutil.copy(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(_SCREAMING_SNAKE_CASE ): shutil.copy(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() __a = os.path.join(_SCREAMING_SNAKE_CASE , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: __a = eval_result if best_iteration is None: __a = new_iteration __a = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: __a = new_iteration __a = new_eval_result __a = 0 else: if new_eval_result == best_eval_result: __a = new_iteration __a = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: __a = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''' , _SCREAMING_SNAKE_CASE ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , _SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_SCREAMING_SNAKE_CASE , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(_SCREAMING_SNAKE_CASE , '''eval_results_best-iteration.json''' ) , ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''' , args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , _SCREAMING_SNAKE_CASE ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_SCREAMING_SNAKE_CASE , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(_SCREAMING_SNAKE_CASE , '''eval_results_best-iteration.json''' ) , )
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = KandinskyVaaImgaImgPipeline __UpperCAmelCase : Optional[Any] = ['image_embeds', 'negative_image_embeds', 'image'] __UpperCAmelCase : Dict = [ 'image_embeds', 'negative_image_embeds', 'image', ] __UpperCAmelCase : Any = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] __UpperCAmelCase : List[str] = False @property def __UpperCAmelCase ( self ): return 32 @property def __UpperCAmelCase ( self ): return 32 @property def __UpperCAmelCase ( self ): return self.time_input_dim @property def __UpperCAmelCase ( self ): return self.time_input_dim * 4 @property def __UpperCAmelCase ( self ): return 100 @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = { '''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, } __a = UNetaDConditionModel(**_a ) return model @property def __UpperCAmelCase ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCAmelCase ( self ): __a = self.dummy_unet __a = self.dummy_movq __a = { '''num_train_timesteps''': 1_000, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } __a = DDIMScheduler(**_a ) __a = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __UpperCAmelCase ( self , _a , _a=0 ): __a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_a ) ).to(_a ) __a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _a ) # create init_image __a = floats_tensor((1, 3, 64, 64) , rng=random.Random(_a ) ).to(_a ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(_a ) ).convert('''RGB''' ).resize((256, 256) ) if str(_a ).startswith('''mps''' ): __a = torch.manual_seed(_a ) else: __a = torch.Generator(device=_a ).manual_seed(_a ) __a = { '''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 __UpperCAmelCase ( self ): __a = '''cpu''' __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) __a = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = pipe(**self.get_dummy_inputs(_a ) ) __a = output.images __a = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] __a = image[0, -3:, -3:, -1] __a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a = np.array( [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] ) 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 __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): __a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) __a = '''A red cartoon frog, 4k''' __a = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_a ) __a = KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) __a = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) __a = torch.Generator(device='''cpu''' ).manual_seed(0 ) __a = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() __a = pipeline( image=_a , image_embeds=_a , negative_image_embeds=_a , generator=_a , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , ) __a = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_a , _a )
351
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'funnel' __UpperCAmelCase : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', } def __init__( self , _a=30_522 , _a=[4, 4, 4] , _a=None , _a=2 , _a=768 , _a=12 , _a=64 , _a=3_072 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=None , _a=1E-9 , _a="mean" , _a="relative_shift" , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = block_sizes __a = [1] * len(_a ) if block_repeats is None else block_repeats assert len(_a ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __a = num_decoder_layers __a = d_model __a = n_head __a = d_head __a = d_inner __a = hidden_act __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = initializer_range __a = initializer_std __a = layer_norm_eps assert pooling_type in [ "mean", "max", ], f'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' __a = pooling_type assert attention_type in [ "relative_shift", "factorized", ], f'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' __a = attention_type __a = separate_cls __a = truncate_seq __a = pool_q_only super().__init__(**_a ) @property def __UpperCAmelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.''' ) @property def __UpperCAmelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError('''This model does not support the setting of `num_blocks`. Please set `block_sizes`.''' )
11
0
"""simple docstring""" from scipy.stats import pearsonr import datasets lowercase_ = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' lowercase_ = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' lowercase_ = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def __UpperCAmelCase ( self , _a , _a , _a=False ): if return_pvalue: __a = pearsonr(_a , _a ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(_a , _a )[0] )}
352
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> str: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _a ) __a = image_processor.post_process_semantic_segmentation(outputs=_a ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _a )
11
0
def lowercase ( lowerCAmelCase__ : int = 10 , lowerCAmelCase__ : int = 22 ) -> int: __a = range(1 , _lowerCAmelCase ) __a = range(1 , _lowerCAmelCase ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F'''{solution(1_0, 2_2) = }''')
353
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
11
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = value __a = None __a = None class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = tree def __UpperCAmelCase ( self , _a ): if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self ): yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
354
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __UpperCAmelCase ( self , _a , _a=None , _a="This is a sound of {}." ): if isinstance(_a , _a ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(_a ).content else: with open(_a , '''rb''' ) as f: __a = f.read() if isinstance(_a , _a ): __a = ffmpeg_read(_a , self.feature_extractor.sampling_rate ) if not isinstance(_a , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) __a = candidate_labels __a = [hypothesis_template.format(_a ) for x in candidate_labels] __a = self.tokenizer(_a , return_tensors=self.framework , padding=_a ) __a = [text_inputs] return inputs def __UpperCAmelCase ( self , _a ): __a = model_inputs.pop('''candidate_labels''' ) __a = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _a ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**_a , **_a ) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.pop('''candidate_labels''' ) __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_a , _a ) , key=lambda _a : -x[0] ) ] return result
11
0
"""simple docstring""" from datetime import datetime import requests def lowercase ( lowerCAmelCase__ : Dict ) -> bytes: __a = '''https://downloadgram.net/wp-json/wppress/video-downloader/video?url=''' __a = requests.get(base_url + url ).json()[0]['''urls'''][0]['''src'''] return requests.get(__UpperCAmelCase ).content if __name__ == "__main__": lowercase_ = input("Enter Video/IGTV url: ").strip() lowercase_ = 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}.''')
355
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
11
0
"""simple docstring""" import logging from transformers.configuration_utils import PretrainedConfig lowercase_ = logging.getLogger(__name__) class __lowerCAmelCase ( A__ ): '''simple docstring''' __UpperCAmelCase : str = 'masked_bert' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=0 , _a="topK" , _a="constant" , _a=0.0 , **_a , ): super().__init__(pad_token_id=lowerCamelCase__ , **lowerCamelCase__ ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = pruning_method __a = mask_init __a = mask_scale
356
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : Dict ) -> Any: __a = int(A_ ) if decimal in (0, 1): # Exit cases for the recursion return str(A_ ) __a = divmod(A_ , 2 ) return binary_recursive(A_ ) + str(A_ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = str(A_ ).strip() if not number: raise ValueError('''No input value was provided''' ) __a = '''-''' if number.startswith('''-''' ) else '''''' __a = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return f'''{negative}0b{binary_recursive(int(A_ ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
357
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): self.assertEqual(len(_a ) , len(_a ) ) for a, b in zip(_a , _a ): self.assertAlmostEqual(_a , _a , delta=_a ) def __UpperCAmelCase ( self ): __a = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_a ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def __UpperCAmelCase ( self ): __a = None ops.enable_eager_execution_internal() __a = tf.config.list_physical_devices('''CPU''' ) if len(_a ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a = tf.config.list_logical_devices(device_type='''CPU''' ) __a = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a = GradientAccumulator() __a = tf.Variable([4.0, 3.0] ) __a , __a = create_optimizer(5E-5 , 10 , 5 ) __a = tf.Variable([0.0, 0.0] , trainable=_a ) def accumulate_on_replica(_a ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_a , _a ): with strategy.scope(): __a = strategy.experimental_local_results(_a ) local_variables[0].assign(_a ) local_variables[1].assign(_a ) strategy.run(_a , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_a ) def _check_local_values(_a , _a ): __a = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _a , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _a , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
11
0
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_5_0, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'pytorch', 'script': 'run_ddp.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_0_0, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'tensorflow', 'script': 'run_tf_dist.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_0_0, 'eval_accuracy': 0.6, 'eval_loss': 0.7}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=__A , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): __a = f'''{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}''' # distributed data settings __a = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=__A , instance_count=__A , instance_type=self.instance_type , debugger_hook_config=__A , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=__A , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(__A ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(2,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(__A ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , __A )
358
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: lowercase_ = None lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json", "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json", }, } lowercase_ = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off lowercase_ = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = ['input_ids', 'attention_mask'] __UpperCAmelCase : Optional[Any] = MBartTokenizer __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , **_a , ) __a = vocab_file __a = False if not self.vocab_file else True __a = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __a = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __a = src_lang if src_lang is not None else '''en_XX''' __a = self.convert_tokens_to_ids(self._src_lang ) __a = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __UpperCAmelCase ( self ): return self._src_lang @src_lang.setter def __UpperCAmelCase ( self , _a ): __a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a , _a , _a , **_a ): if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __a = src_lang __a = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) __a = self.convert_tokens_to_ids(_a ) __a = tgt_lang_id return inputs def __UpperCAmelCase ( self , _a , _a = "en_XX" , _a = None , _a = "ro_RO" , **_a , ): __a = src_lang __a = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def __UpperCAmelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __UpperCAmelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a , _a = None ): 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(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return __a = 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 ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
11
0
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowercase_ = 1_6 lowercase_ = 3_2 def lowercase ( lowerCAmelCase__ : Accelerator , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : str = "bert-base-cased" ) -> Optional[int]: __a = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) __a = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(lowerCAmelCase__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __a = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=lowerCAmelCase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(lowerCAmelCase__ : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(lowerCAmelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __a = DataLoader( tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) __a = DataLoader( tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple ) -> List[str]: model.eval() __a = 0 for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a = model(**lowerCAmelCase__ ) __a = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __a = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: __a = predictions[: len(eval_dataloader.dataset ) - samples_seen] __a = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) __a = metric.compute() return eval_metric["accuracy"] def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] ) -> Optional[int]: # Initialize accelerator __a = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config["""lr"""] __a = int(config['''num_epochs'''] ) __a = int(config['''seed'''] ) __a = int(config['''batch_size'''] ) __a = args.model_name_or_path set_seed(lowerCAmelCase__ ) __a = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer __a = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: __a = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: __a = 1 __a = (len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: __a = DummyScheduler(lowerCAmelCase__ , total_num_steps=lowerCAmelCase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over __a = 0 # We also need to keep track of the stating epoch so files are named properly __a = 0 __a = evaluate.load('''glue''' , '''mrpc''' ) __a = num_epochs if args.partial_train_epoch is not None: __a = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) __a = args.resume_from_checkpoint.split('''epoch_''' )[1] __a = """""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break __a = int(lowerCAmelCase__ ) + 1 __a = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) accelerator.print('''resumed checkpoint performance:''' , lowerCAmelCase__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir , f'''state_{starting_epoch-1}.json''' ) , '''r''' ) as f: __a = json.load(lowerCAmelCase__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model __a = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): __a = model(**lowerCAmelCase__ ) __a = outputs.loss __a = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 __a = f'''epoch_{epoch}''' __a = os.path.join(args.output_dir , lowerCAmelCase__ ) accelerator.save_state(lowerCAmelCase__ ) __a = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __a = accuracy __a = lr_scheduler.get_lr()[0] __a = optimizer.param_groups[0]["""lr"""] __a = epoch __a = overall_step accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f'''state_{epoch}.json''' ) , '''w''' ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( ) -> str: __a = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=lowerCAmelCase__ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=lowerCAmelCase__ , ) parser.add_argument( '''--output_dir''' , type=lowerCAmelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--partial_train_epoch''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If passed, the training will stop after this number of epochs.''' , ) parser.add_argument( '''--num_epochs''' , type=lowerCAmelCase__ , default=2 , help='''Number of train epochs.''' , ) __a = parser.parse_args() __a = {"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
359
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging 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.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn 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]\n" class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-question-answering''' ) self.tool.setup() __a = load_tool('''text-question-answering''' , remote=_a ) def __UpperCAmelCase ( self ): __a = self.tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' )
11
0
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : Path , lowerCAmelCase__ : str = None , lowerCAmelCase__ : str = None , lowerCAmelCase__ : str = None , ) -> str: if config_name_or_path is None: __a = '''facebook/rag-token-base''' if model_type == '''rag_token''' else '''facebook/rag-sequence-base''' if generator_tokenizer_name_or_path is None: __a = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: __a = question_encoder_name_or_path __a = RagTokenForGeneration if model_type == '''rag_token''' else RagSequenceForGeneration # Save model. __a = RagConfig.from_pretrained(_a ) __a = AutoConfig.from_pretrained(_a ) __a = AutoConfig.from_pretrained(_a ) __a = gen_config __a = question_encoder_config __a = model_class.from_pretrained_question_encoder_generator( _a , _a , config=_a ) rag_model.save_pretrained(_a ) # Sanity check. model_class.from_pretrained(_a ) # Save tokenizers. __a = AutoTokenizer.from_pretrained(_a ) gen_tokenizer.save_pretrained(dest_dir / '''generator_tokenizer/''' ) __a = AutoTokenizer.from_pretrained(_a ) question_encoder_tokenizer.save_pretrained(dest_dir / '''question_encoder_tokenizer/''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( "--model_type", choices=["rag_sequence", "rag_token"], required=True, type=str, help="RAG model type: rag_sequence, rag_token", ) parser.add_argument("--dest", type=str, required=True, help="Path to the output checkpoint directory.") parser.add_argument("--generator_name_or_path", type=str, required=True, help="Generator model identifier") parser.add_argument( "--question_encoder_name_or_path", type=str, required=True, help="Question encoder model identifier" ) parser.add_argument( "--generator_tokenizer_name_or_path", type=str, help="Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``", ) parser.add_argument( "--question_encoder_tokenizer_name_or_path", type=str, help="Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``", ) parser.add_argument( "--config_name_or_path", type=str, help=( "Identifier of the model config to use, if not provided, resolves to a base config for a given" " ``model_type``" ), ) lowercase_ = parser.parse_args() lowercase_ = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig", ], "processing_blip_2": ["Blip2Processor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Blip2Model", "Blip2QFormerModel", "Blip2PreTrainedModel", "Blip2ForConditionalGeneration", "Blip2VisionModel", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> list: if len(__lowerCAmelCase ) <= 1: return [tuple(__lowerCAmelCase )] __a = [] def generate(lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , __lowerCAmelCase ) for i in range(k - 1 ): if k % 2 == 0: # k is even __a = arr[k - 1], arr[i] else: # k is odd __a = arr[k - 1], arr[0] generate(k - 1 , __lowerCAmelCase ) generate(len(__lowerCAmelCase ) , __lowerCAmelCase ) return res if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] print(heaps(arr))
361
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a = len(lowerCAmelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCAmelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCAmelCase__ , lowerCAmelCase__ , ) def lowercase ( lowerCAmelCase__ : int ) -> None: __a = [] depth_first_search([] , [] , [] , lowerCAmelCase__ , lowerCAmelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCAmelCase__ ) print('''''' ) print(len(lowerCAmelCase__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
11
0
"""simple docstring""" import os import pytest from transformers.dynamic_module_utils import get_imports lowercase_ = ''' import os ''' lowercase_ = ''' def foo(): import os return False ''' lowercase_ = ''' def foo(): def bar(): if True: import os return False return bar() ''' lowercase_ = ''' import os try: import bar except ImportError: raise ValueError() ''' lowercase_ = ''' import os def foo(): try: import bar except ImportError: raise ValueError() ''' lowercase_ = ''' import os try: import bar except (ImportError, AttributeError): raise ValueError() ''' lowercase_ = ''' import os try: import bar except ImportError as e: raise ValueError() ''' lowercase_ = ''' import os try: import bar except: raise ValueError() ''' lowercase_ = ''' import os try: import bar import baz except ImportError: raise ValueError() ''' lowercase_ = ''' import os try: import bar import baz except ImportError: x = 1 raise ValueError() ''' lowercase_ = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('''case''' , _lowercase ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = os.path.join(_lowercase , '''test_file.py''' ) with open(_lowercase , '''w''' ) as _tmp_file: _tmp_file.write(_lowercase ) __a = get_imports(_lowercase ) assert parsed_imports == ["os"]
362
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
11
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowercase_ = {"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""SpeechEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""FlaxSpeechEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
363
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = 'vit_mae' def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=True , _a=16 , _a=512 , _a=8 , _a=2_048 , _a=0.75 , _a=False , **_a , ): super().__init__(**_a ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = decoder_num_attention_heads __a = decoder_hidden_size __a = decoder_num_hidden_layers __a = decoder_intermediate_size __a = mask_ratio __a = norm_pix_loss
11
0
"""simple docstring""" import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __lowerCAmelCase = "\\n Text data.\n Second line of data." __lowerCAmelCase = "file" @pytest.fixture(scope='''session''' ) def lowercase ( lowerCAmelCase__ : str ) -> Optional[int]: __a = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''') __a = bytes(snake_case__ , '''utf-8''' ) with zstd.open(snake_case__ , '''wb''' ) as f: f.write(snake_case__ ) return path @pytest.fixture def lowercase ( lowerCAmelCase__ : List[Any] ) -> List[Any]: with open(os.path.join(tmpfs.local_root_dir , snake_case__ ) , '''w''' ) as f: f.write(snake_case__ ) return FILE_PATH @pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ) -> Optional[Any]: __a = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path} __a = input_paths[compression_format] __a = tmp_path / '''cache''' __a = DownloadConfig(cache_dir=snake_case__ , extract_compressed_file=snake_case__ ) __a = cached_path(snake_case__ , download_config=snake_case__ ) with open(snake_case__ ) as f: __a = f.read() with open(snake_case__ ) as f: __a = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('''default_extracted''' , [True, False] ) @pytest.mark.parametrize('''default_cache_dir''' , [True, False] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ) -> List[str]: __a = '''custom_cache''' __a = '''custom_extracted_dir''' __a = tmp_path / '''custom_extracted_path''' if default_extracted: __a = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''') else: monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , snake_case__ ) monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(snake_case__ ) ) __a = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __a = xz_file __a = ( DownloadConfig(extract_compressed_file=snake_case__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=snake_case__ ) ) __a = cached_path(snake_case__ , download_config=snake_case__ ) assert Path(snake_case__ ).parent.parts[-2:] == expected def lowercase ( lowerCAmelCase__ : Tuple ) -> Union[str, Any]: # absolute path __a = str(Path(snake_case__ ).resolve() ) assert cached_path(snake_case__ ) == text_file # relative path __a = str(Path(snake_case__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(snake_case__ ) == text_file def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]: # absolute path __a = str(tmp_path.resolve() / '''__missing_file__.txt''' ) with pytest.raises(snake_case__ ): cached_path(snake_case__ ) # relative path __a = '''./__missing_file__.txt''' with pytest.raises(snake_case__ ): cached_path(snake_case__ ) def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: __a = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(snake_case__ ) as f: __a = f.read() assert output_file_content == FILE_CONTENT @patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case__ ) def lowercase ( ) -> List[str]: with pytest.raises(snake_case__ ): cached_path('''https://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case__ ) def lowercase ( lowerCAmelCase__ : List[str] ) -> Tuple: __a = tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(snake_case__ ): http_get('''https://huggingface.co''' , temp_file=snake_case__ ) with pytest.raises(snake_case__ ): http_head('''https://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case__ ) def lowercase ( lowerCAmelCase__ : Optional[int] ) -> List[Any]: __a = tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(snake_case__ ): ftp_get('''ftp://huggingface.co''' , temp_file=snake_case__ ) with pytest.raises(snake_case__ ): ftp_head('''ftp://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case__ ) def lowercase ( lowerCAmelCase__ : int ) -> int: __a = tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(snake_case__ ): fsspec_get('''s3://huggingface.co''' , temp_file=snake_case__ ) with pytest.raises(snake_case__ ): fsspec_head('''s3://huggingface.co''' )
364
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Optional[int] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
11
0
"""simple docstring""" from math import isqrt, loga def lowercase ( lowerCAmelCase__ : int ) -> Optional[int]: __a = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , lowerCAmelCase__ , lowerCAmelCase__ ): __a = False return [i for i in range(2 , lowerCAmelCase__ ) if is_prime[i]] def lowercase ( lowerCAmelCase__ : int = 800800 , lowerCAmelCase__ : int = 800800 ) -> Optional[Any]: __a = degree * loga(lowerCAmelCase__ ) __a = int(lowerCAmelCase__ ) __a = calculate_prime_numbers(lowerCAmelCase__ ) __a = 0 __a = 0 __a = len(lowerCAmelCase__ ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F'''{solution() = }''')
365
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
11
0
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() lowercase_ = { "bart": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), "bert": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-cased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-base-cased-finetuned-mrpc": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "dpr": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), "gpt2": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlnet": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm-roberta": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "transfo-xl": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "openai-gpt": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "roberta": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "layoutlm": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), "roberta-large-mnli": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "camembert": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "flaubert": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert-base-distilled-squad": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert-visual-feature-encoder": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "ctrl": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "albert": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "t5": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "electra": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "wav2vec2": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict=False , lowerCAmelCase__ : Union[str, Any]=True ) -> Union[str, Any]: if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) __a = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __a = cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) __a = config_class.from_json_file(SCREAMING_SNAKE_CASE__ ) __a = True __a = True print(f'''Building TensorFlow model from configuration: {config}''' ) __a = model_class(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __a = cached_file( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __a = load_pytorch_checkpoint_in_tfa_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if compare_with_pt_model: __a = tf_model(tf_model.dummy_inputs , training=SCREAMING_SNAKE_CASE__ ) # build the network __a = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) __a = pt_model_class.from_pretrained( pretrained_model_name_or_path=SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ , state_dict=SCREAMING_SNAKE_CASE__ ) with torch.no_grad(): __a = pt_model(**pt_model.dummy_inputs ) __a = pto[0].numpy() __a = tfo[0].numpy() __a = np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2e-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(SCREAMING_SNAKE_CASE__ , save_format='''h5''' ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int]=None , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : Optional[Any]=False , lowerCAmelCase__ : Dict=False , lowerCAmelCase__ : int=False , lowerCAmelCase__ : Optional[Any]=False , ) -> List[str]: if args_model_type is None: __a = list(MODEL_CLASSES.keys() ) else: __a = [args_model_type] for j, model_type in enumerate(SCREAMING_SNAKE_CASE__ , start=1 ): print('''=''' * 100 ) print(f''' Converting model type {j}/{len(SCREAMING_SNAKE_CASE__ )}: {model_type}''' ) print('''=''' * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) __a = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __a = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __a = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , start=1 ): print('''-''' * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue __a = model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(SCREAMING_SNAKE_CASE__ )}: {model_shortcut_name} - model_type {model_type}''' ) print('''-''' * 100 ) if config_shortcut_name in aws_config_map: __a = cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) else: __a = config_shortcut_name if model_shortcut_name in aws_model_maps: __a = cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) else: __a = model_shortcut_name if os.path.isfile(SCREAMING_SNAKE_CASE__ ): __a = '''converted_model''' convert_pt_checkpoint_to_tf( model_type=SCREAMING_SNAKE_CASE__ , pytorch_checkpoint_path=SCREAMING_SNAKE_CASE__ , config_file=SCREAMING_SNAKE_CASE__ , tf_dump_path=os.path.join(SCREAMING_SNAKE_CASE__ , model_shortcut_name + '''-tf_model.h5''' ) , compare_with_pt_model=SCREAMING_SNAKE_CASE__ , ) if remove_cached_files: os.remove(SCREAMING_SNAKE_CASE__ ) os.remove(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( F'''Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ''' "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") lowercase_ = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
366
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'rwkv' __UpperCAmelCase : Optional[Any] = {'max_position_embeddings': 'context_length'} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): __a = vocab_size __a = context_length __a = hidden_size __a = num_hidden_layers __a = attention_hidden_size if attention_hidden_size is not None else hidden_size __a = intermediate_size if intermediate_size is not None else 4 * hidden_size __a = layer_norm_epsilon __a = rescale_every __a = use_cache __a = bos_token_id __a = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
11
0
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : nn.Module __UpperCAmelCase : List[nn.Module] = field(default_factory=_a ) __UpperCAmelCase : list = field(default_factory=_a ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = len(list(m.modules() ) ) == 1 or isinstance(_a , nn.Convad ) or isinstance(_a , nn.BatchNormad ) if has_not_submodules: self.traced.append(_a ) def __call__( self , _a ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_a ) [x.remove() for x in self.handles] return self @property def __UpperCAmelCase ( self ): return list(filter(lambda _a : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : nn.Module __UpperCAmelCase : nn.Module __UpperCAmelCase : int = 0 __UpperCAmelCase : List = field(default_factory=_a ) __UpperCAmelCase : List = field(default_factory=_a ) def __call__( self , _a ): __a = Tracker(self.dest )(_a ).parametrized __a = Tracker(self.src )(_a ).parametrized __a = list(filter(lambda _a : type(_a ) not in self.src_skip , _a ) ) __a = list(filter(lambda _a : type(_a ) not in self.dest_skip , _a ) ) if len(_a ) != len(_a ): raise Exception( f'''Numbers of operations are different. Source module has {len(_a )} operations while''' f''' destination module has {len(_a )}.''' ) for dest_m, src_m in zip(_a , _a ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'''Transfered from={src_m} to={dest_m}''' ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple = True ) -> Optional[Any]: print(f'''Converting {name}...''' ) with torch.no_grad(): __a = timm.create_model(lowerCamelCase_ , pretrained=lowerCamelCase_ ).eval() __a = ResNetForImageClassification(lowerCamelCase_ ).eval() __a = ModuleTransfer(src=lowerCamelCase_ , dest=lowerCamelCase_ ) __a = torch.randn((1, 3, 224, 224) ) module_transfer(lowerCamelCase_ ) assert torch.allclose(from_model(lowerCamelCase_ ) , our_model(lowerCamelCase_ ).logits ), "The model logits don't match the original one." __a = f'''resnet{'-'.join(name.split('resnet' ) )}''' print(lowerCamelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=lowerCamelCase_ , ) # we can use the convnext one __a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=lowerCamelCase_ , ) print(f'''Pushed {checkpoint_name}''' ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Dict = True ) -> List[str]: __a = 'imagenet-1k-id2label.json' __a = 1000 __a = (1, num_labels) __a = 'huggingface/label-files' __a = num_labels __a = json.load(open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type='''dataset''' ) , '''r''' ) ) __a = {int(lowerCamelCase_ ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} __a = partial(lowerCamelCase_ , num_labels=lowerCamelCase_ , idalabel=lowerCamelCase_ , labelaid=lowerCamelCase_ ) __a = { 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(lowerCamelCase_ , names_to_config[model_name] , lowerCamelCase_ , lowerCamelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
367
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = (UnCLIPScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCAmelCase ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_a , prev_timestep=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''fixed_small_log''' ) __a = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''learned_range''' ) __a = scheduler_class(**_a ) __a = 0.5 assert scheduler._get_variance(1 , predicted_variance=_a ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_a ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_a ) - -0.001_0011 < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(25 ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) if i + 1 == timesteps.shape[0]: __a = None else: __a = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a = scheduler.step( _a , _a , _a , prev_timestep=_a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass
11
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowercase_ = None lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} lowercase_ = { "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", }, "tokenizer_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json", }, } lowercase_ = { "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, } lowercase_ = "▁" class __lowerCAmelCase ( __a ): '''simple docstring''' __UpperCAmelCase : Any = VOCAB_FILES_NAMES __UpperCAmelCase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : List[str] = AlbertTokenizer def __init__( self , _a=None , _a=None , _a=True , _a=True , _a=False , _a="[CLS]" , _a="[SEP]" , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , **_a , ): __a = ( AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ , normalized=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , do_lower_case=UpperCamelCase__ , remove_space=UpperCamelCase__ , keep_accents=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , **UpperCamelCase__ , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [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 __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [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 , _a , _a = None ): 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 __a = 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__ ) return (out_vocab_file,)
368
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
11
0
"""simple docstring""" import re import string import numpy as np import datasets lowercase_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' lowercase_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' lowercase_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , reference_urls=[] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=False , _a=False , _a=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: __a = np.array([re.sub(_lowercase , '''''' , _lowercase ) for x in predictions] ) __a = np.array([re.sub(_lowercase , '''''' , _lowercase ) for x in references] ) else: __a = np.asarray(_lowercase ) __a = np.asarray(_lowercase ) if ignore_case: __a = np.char.lower(_lowercase ) __a = np.char.lower(_lowercase ) if ignore_punctuation: __a = string.punctuation.maketrans('''''' , '''''' , string.punctuation ) __a = np.char.translate(_lowercase , table=_lowercase ) __a = np.char.translate(_lowercase , table=_lowercase ) if ignore_numbers: __a = string.digits.maketrans('''''' , '''''' , string.digits ) __a = np.char.translate(_lowercase , table=_lowercase ) __a = np.char.translate(_lowercase , table=_lowercase ) __a = predictions == references return {"exact_match": np.mean(_lowercase ) * 100}
369
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
0
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL lowercase_ = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : tuple , lowerCAmelCase__ : Path , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int]=False , ) -> Union[str, Any]: output_path.parent.mkdir(parents=a__ , exist_ok=a__ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( a__ , a__ , f=output_path.as_posix() , input_names=a__ , output_names=a__ , dynamic_axes=a__ , do_constant_folding=a__ , use_external_data_format=a__ , enable_onnx_checker=a__ , opset_version=a__ , ) else: export( a__ , a__ , f=output_path.as_posix() , input_names=a__ , output_names=a__ , dynamic_axes=a__ , do_constant_folding=a__ , opset_version=a__ , ) @torch.no_grad() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : bool = False ) -> int: __a = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __a = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: __a = '''cpu''' __a = Path(a__ ) # VAE DECODER __a = AutoencoderKL.from_pretrained(model_path + '''/vae''' ) __a = vae_decoder.config.latent_channels # forward only through the decoder part __a = vae_decoder.decode onnx_export( a__ , model_args=( torch.randn(1 , a__ , 25 , 25 ).to(device=a__ , dtype=a__ ), False, ) , output_path=output_path / '''vae_decoder''' / '''model.onnx''' , ordered_input_names=['''latent_sample''', '''return_dict'''] , output_names=['''sample'''] , dynamic_axes={ '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=a__ , ) del vae_decoder if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=1_4, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") lowercase_ = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
370
"""simple docstring""" from math import factorial, radians def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 18 , lowerCAmelCase__ : int = 10 ) -> float: __a = angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians __a = radians(lowerCAmelCase__ ) __a = angle_in_radians __a = 3 __a = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) __a = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__("doctest").testmod()
11
0
"""simple docstring""" import comet # From: unbabel-comet import torch import datasets lowercase_ = datasets.logging.get_logger(__name__) lowercase_ = "\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel's Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = \"{COMET}: A Neural Framework for {MT} Evaluation\",\n author = \"Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon\",\n booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\",\n month = nov,\n year = \"2020\",\n address = \"Online\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\",\n pages = \"2685--2702\",\n}\n" lowercase_ = "\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n" lowercase_ = "\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric('comet')\n >>> # comet_metric = load_metric('comet', 'wmt20-comet-da') # you can also choose which model to use\n >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"]\n >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"]\n >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results[\"scores\"]])\n [0.19, 0.92]\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://unbabel.github.io/COMET/html/index.html''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''sources''': datasets.Value('''string''' , id='''sequence''' ), '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/Unbabel/COMET'''] , reference_urls=[ '''https://github.com/Unbabel/COMET''', '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''', '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''', ] , ) def __UpperCAmelCase ( self , _a ): if self.config_name == "default": __a = comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) ) else: __a = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def __UpperCAmelCase ( self , _a , _a , _a , _a=None , _a=False ): if gpus is None: __a = 1 if torch.cuda.is_available() else 0 __a = {'src': sources, 'mt': predictions, 'ref': references} __a = [dict(zip(_A , _A ) ) for t in zip(*data.values() )] __a = self.scorer.predict(_A , gpus=_A , progress_bar=_A ) return {"mean_score": mean_score, "scores": scores}
371
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : dict ) -> tuple: return (data["data"], data["target"]) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ) -> np.ndarray: __a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowerCAmelCase__ , lowerCAmelCase__ ) # Predict target for test data __a = xgb.predict(lowerCAmelCase__ ) __a = predictions.reshape(len(lowerCAmelCase__ ) , 1 ) return predictions def lowercase ( ) -> None: __a = fetch_california_housing() __a , __a = data_handling(lowerCAmelCase__ ) __a , __a , __a , __a = train_test_split( lowerCAmelCase__ , lowerCAmelCase__ , test_size=0.25 , random_state=1 ) __a = xgboost(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
11
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class __lowerCAmelCase ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = 'roformer' def __init__( self , _a=50_000 , _a=None , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=1_536 , _a=2 , _a=0.02 , _a=1E-12 , _a=0 , _a=False , _a=True , **_a , ): super().__init__(pad_token_id=_a , **_a ) __a = vocab_size __a = hidden_size if embedding_size is None else embedding_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = rotary_value __a = use_cache class __lowerCAmelCase ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("T") def lowercase ( lowerCAmelCase__ : int ) -> Any: return (position - 1) // 2 def lowercase ( lowerCAmelCase__ : int ) -> Optional[int]: return (2 * position) + 1 def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: return (2 * position) + 2 class __lowerCAmelCase ( Generic[T] ): '''simple docstring''' def __init__( self ): __a = [] __a = {} __a = 0 def __len__( self ): return self.elements def __repr__( self ): return str(self.heap ) def __UpperCAmelCase ( self ): # Check if the priority queue is empty return self.elements == 0 def __UpperCAmelCase ( self , _a , _a ): # Add an element with given priority to the queue self.heap.append((elem, weight) ) __a = self.elements self.elements += 1 self._bubble_up(snake_case_ ) def __UpperCAmelCase ( self ): # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a = self.heap[0] self._bubble_down(snake_case_ ) return elem def __UpperCAmelCase ( self , _a , _a ): # Update the weight of the given key __a = self.position_map[elem] __a = (elem, weight) if position > 0: __a = get_parent_position(snake_case_ ) __a = self.heap[parent_position] if parent_weight > weight: self._bubble_up(snake_case_ ) else: self._bubble_down(snake_case_ ) else: self._bubble_down(snake_case_ ) def __UpperCAmelCase ( self , _a ): # Place a node at the proper position (upward movement) [to be used internally # only] __a = self.position_map[elem] if curr_pos == 0: return None __a = get_parent_position(snake_case_ ) __a = self.heap[curr_pos] __a = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(snake_case_ , snake_case_ ) return self._bubble_up(snake_case_ ) return None def __UpperCAmelCase ( self , _a ): # Place a node at the proper position (downward movement) [to be used # internally only] __a = self.position_map[elem] __a = self.heap[curr_pos] __a = get_child_left_position(snake_case_ ) __a = get_child_right_position(snake_case_ ) if child_left_position < self.elements and child_right_position < self.elements: __a = self.heap[child_left_position] __a = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(snake_case_ , snake_case_ ) return self._bubble_down(snake_case_ ) if child_left_position < self.elements: __a = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(snake_case_ , snake_case_ ) return self._bubble_down(snake_case_ ) else: return None if child_right_position < self.elements: __a = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(snake_case_ , snake_case_ ) return self._bubble_down(snake_case_ ) return None def __UpperCAmelCase ( self , _a , _a ): # Swap the nodes at the given positions __a = self.heap[nodea_pos][0] __a = self.heap[nodea_pos][0] __a = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a = nodea_pos __a = nodea_pos class __lowerCAmelCase ( Generic[T] ): '''simple docstring''' def __init__( self ): __a = {} __a = 0 def __repr__( self ): return str(self.connections ) def __len__( self ): return self.nodes def __UpperCAmelCase ( self , _a ): # Add a node in the graph if it is not in the graph if node not in self.connections: __a = {} self.nodes += 1 def __UpperCAmelCase ( self , _a , _a , _a ): # Add an edge between 2 nodes in the graph self.add_node(snake_case_ ) self.add_node(snake_case_ ) __a = weight __a = weight def lowercase ( lowerCAmelCase__ : GraphUndirectedWeighted[T] , ) -> int: __a = {node: maxsize for node in graph.connections} __a = {node: None for node in graph.connections} __a = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCAmelCase__ , lowerCAmelCase__ ) if priority_queue.is_empty(): return dist, parent # initialization __a = priority_queue.extract_min() __a = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase__ , dist[neighbour] ) __a = node # running prim's algorithm while not priority_queue.is_empty(): __a = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase__ , dist[neighbour] ) __a = node return dist, parent
351
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'funnel' __UpperCAmelCase : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', } def __init__( self , _a=30_522 , _a=[4, 4, 4] , _a=None , _a=2 , _a=768 , _a=12 , _a=64 , _a=3_072 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=None , _a=1E-9 , _a="mean" , _a="relative_shift" , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = block_sizes __a = [1] * len(_a ) if block_repeats is None else block_repeats assert len(_a ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __a = num_decoder_layers __a = d_model __a = n_head __a = d_head __a = d_inner __a = hidden_act __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = initializer_range __a = initializer_std __a = layer_norm_eps assert pooling_type in [ "mean", "max", ], f'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' __a = pooling_type assert attention_type in [ "relative_shift", "factorized", ], f'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' __a = attention_type __a = separate_cls __a = truncate_seq __a = pool_q_only super().__init__(**_a ) @property def __UpperCAmelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.''' ) @property def __UpperCAmelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError('''This model does not support the setting of `num_blocks`. Please set `block_sizes`.''' )
11
0
"""simple docstring""" import warnings from .generation import TFGenerationMixin class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' warnings.warn( 'Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will ' 'be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.' , __SCREAMING_SNAKE_CASE , )
352
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> str: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _a ) __a = image_processor.post_process_semantic_segmentation(outputs=_a ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _a )
11
0
from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, 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.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=1_000 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = range_bbox def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # convert bbox to numpy since TF does not support item assignment __a = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a = bbox[i, j, 3] __a = bbox[i, j, 1] __a = t if bbox[i, j, 2] < bbox[i, j, 0]: __a = bbox[i, j, 2] __a = bbox[i, j, 0] __a = t __a = tf.convert_to_tensor(a__ ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = LayoutLMConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a ): __a = TFLayoutLMModel(config=a__ ) __a = model(a__ , a__ , attention_mask=a__ , token_type_ids=a__ ) __a = model(a__ , a__ , token_type_ids=a__ ) __a = model(a__ , a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a ): __a = TFLayoutLMForMaskedLM(config=a__ ) __a = model(a__ , a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFLayoutLMForSequenceClassification(config=a__ ) __a = model(a__ , a__ , attention_mask=a__ , token_type_ids=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFLayoutLMForTokenClassification(config=a__ ) __a = model(a__ , a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a ): __a = TFLayoutLMForQuestionAnswering(config=a__ ) __a = model(a__ , a__ , attention_mask=a__ , token_type_ids=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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_tf class __lowerCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) __UpperCAmelCase : List[Any] = ( { "feature-extraction": TFLayoutLMModel, "fill-mask": TFLayoutLMForMaskedLM, "text-classification": TFLayoutLMForSequenceClassification, "token-classification": TFLayoutLMForTokenClassification, "zero-shot": TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : int = True __UpperCAmelCase : List[str] = 1_0 def __UpperCAmelCase ( self ): __a = TFLayoutLMModelTester(self ) __a = ConfigTester(self , config_class=a__ , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a__ ) @slow def __UpperCAmelCase ( self ): for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFLayoutLMModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @unittest.skip('''Onnx compliancy broke with TF 2.10''' ) def __UpperCAmelCase ( self ): pass def lowercase ( ) -> Optional[int]: __a = tf.convert_to_tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]] ) # noqa: E231 __a = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 __a = tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ) # noqa: E231 __a = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) __a = tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFLayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased''' ) __a , __a , __a , __a , __a = prepare_layoutlm_batch_inputs() # forward pass __a = model(input_ids=a__ , bbox=a__ , attention_mask=a__ , token_type_ids=a__ ) # test the sequence output on [0, :3, :3] __a = tf.convert_to_tensor( [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a__ , atol=1E-3 ) ) # test the pooled output on [1, :3] __a = tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , a__ , atol=1E-3 ) ) @slow def __UpperCAmelCase ( self ): __a = TFLayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=2 ) __a , __a , __a , __a , __a = prepare_layoutlm_batch_inputs() # forward pass __a = model( input_ids=a__ , bbox=a__ , attention_mask=a__ , token_type_ids=a__ , labels=tf.convert_to_tensor([1, 1] ) , ) # test whether we get a loss as a scalar __a = outputs.loss __a = (2,) self.assertEqual(loss.shape , a__ ) # test the shape of the logits __a = outputs.logits __a = (2, 2) self.assertEqual(logits.shape , a__ ) @slow def __UpperCAmelCase ( self ): __a = TFLayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=13 ) __a , __a , __a , __a , __a = prepare_layoutlm_batch_inputs() # forward pass __a = model( input_ids=a__ , bbox=a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) # test the shape of the logits __a = outputs.logits __a = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape , a__ ) @slow def __UpperCAmelCase ( self ): __a = TFLayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased''' ) __a , __a , __a , __a , __a = prepare_layoutlm_batch_inputs() # forward pass __a = model(input_ids=a__ , bbox=a__ , attention_mask=a__ , token_type_ids=a__ ) # test the shape of the logits __a = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape , a__ ) self.assertEqual(outputs.end_logits.shape , a__ )
353
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
11
0
"""simple docstring""" import argparse from collections import defaultdict import yaml lowercase_ = "docs/source/en/_toctree.yml" def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a = defaultdict(lowerCAmelCase__ ) __a = [] __a = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(lowerCAmelCase__ ) __a = new_doc_list __a = [key for key, value in counts.items() if value > 1] __a = [] for duplicate_key in duplicates: __a = list({doc['''title'''] for doc in doc_list if doc['''local'''] == duplicate_key} ) if len(lowerCAmelCase__ ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) __a = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(lowerCAmelCase__ ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(lowerCAmelCase__ ) # Sort return overview_doc def lowercase ( lowerCAmelCase__ : List[str]=False ) -> Tuple: with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: __a = yaml.safe_load(f.read() ) # Get to the API doc __a = 0 while content[api_idx]["title"] != "API": api_idx += 1 __a = content[api_idx]['''sections'''] # Then to the model doc __a = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 __a = api_doc[scheduler_idx]['''sections'''] __a = clean_doc_toc(lowerCAmelCase__ ) __a = False if new_scheduler_doc != scheduler_doc: __a = True if overwrite: __a = new_scheduler_doc if diff: if overwrite: __a = api_doc with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(lowerCAmelCase__ , allow_unicode=lowerCAmelCase__ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) def lowercase ( lowerCAmelCase__ : int=False ) -> List[Any]: with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: __a = yaml.safe_load(f.read() ) # Get to the API doc __a = 0 while content[api_idx]["title"] != "API": api_idx += 1 __a = content[api_idx]['''sections'''] # Then to the model doc __a = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 __a = False __a = api_doc[pipeline_idx]['''sections'''] __a = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: __a = pipeline_doc['''section'''] __a = clean_doc_toc(lowerCAmelCase__ ) if overwrite: __a = new_sub_pipeline_doc new_pipeline_docs.append(lowerCAmelCase__ ) # sort overall pipeline doc __a = clean_doc_toc(lowerCAmelCase__ ) if new_pipeline_docs != pipeline_docs: __a = True if overwrite: __a = new_pipeline_docs if diff: if overwrite: __a = api_doc with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(lowerCAmelCase__ , allow_unicode=lowerCAmelCase__ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowercase_ = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
354
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __UpperCAmelCase ( self , _a , _a=None , _a="This is a sound of {}." ): if isinstance(_a , _a ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(_a ).content else: with open(_a , '''rb''' ) as f: __a = f.read() if isinstance(_a , _a ): __a = ffmpeg_read(_a , self.feature_extractor.sampling_rate ) if not isinstance(_a , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) __a = candidate_labels __a = [hypothesis_template.format(_a ) for x in candidate_labels] __a = self.tokenizer(_a , return_tensors=self.framework , padding=_a ) __a = [text_inputs] return inputs def __UpperCAmelCase ( self , _a ): __a = model_inputs.pop('''candidate_labels''' ) __a = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _a ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**_a , **_a ) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.pop('''candidate_labels''' ) __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_a , _a ) , key=lambda _a : -x[0] ) ] return result
11
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class __lowerCAmelCase ( lowerCamelCase__ ): '''simple docstring''' __UpperCAmelCase : Tuple = 'unispeech-sat' def __init__( self , _a=32 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.0 , _a=0.1 , _a=0.1 , _a=0.02 , _a=1E-5 , _a="group" , _a="gelu" , _a=(512, 512, 512, 512, 512, 512, 512) , _a=(5, 2, 2, 2, 2, 2, 2) , _a=(10, 3, 3, 3, 3, 2, 2) , _a=False , _a=128 , _a=16 , _a=False , _a=True , _a=0.05 , _a=10 , _a=2 , _a=0.0 , _a=10 , _a=0 , _a=320 , _a=2 , _a=0.1 , _a=100 , _a=256 , _a=256 , _a=0.1 , _a="mean" , _a=False , _a=False , _a=256 , _a=(512, 512, 512, 512, 1_500) , _a=(5, 3, 3, 1, 1) , _a=(1, 2, 3, 1, 1) , _a=512 , _a=0 , _a=1 , _a=2 , _a=504 , **_a , ): super().__init__(**__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase ) __a = hidden_size __a = feat_extract_norm __a = feat_extract_activation __a = list(__lowerCamelCase ) __a = list(__lowerCamelCase ) __a = list(__lowerCamelCase ) __a = conv_bias __a = num_conv_pos_embeddings __a = num_conv_pos_embedding_groups __a = len(self.conv_dim ) __a = num_hidden_layers __a = intermediate_size __a = hidden_act __a = num_attention_heads __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = feat_proj_dropout __a = final_dropout __a = layerdrop __a = layer_norm_eps __a = initializer_range __a = vocab_size __a = num_clusters __a = do_stable_layer_norm __a = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a = apply_spec_augment __a = mask_time_prob __a = mask_time_length __a = mask_time_min_masks __a = mask_feature_prob __a = mask_feature_length __a = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a = num_codevectors_per_group __a = num_codevector_groups __a = contrastive_logits_temperature __a = feat_quantizer_dropout __a = num_negatives __a = codevector_dim __a = proj_codevector_dim __a = diversity_loss_weight # ctc loss __a = ctc_loss_reduction __a = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. __a = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __a = list(__lowerCamelCase ) __a = list(__lowerCamelCase ) __a = list(__lowerCamelCase ) __a = xvector_output_dim @property def __UpperCAmelCase ( self ): return functools.reduce(operator.mul , self.conv_stride , 1 )
355
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
11
0
"""simple docstring""" from __future__ import annotations from math import pi def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ) -> 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()
356
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> Tuple: def constraint_to_multiple_of(lowerCAmelCase__ : int , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any]=0 , lowerCAmelCase__ : Optional[Any]=None ): __a = round(val / multiple ) * multiple if max_val is not None and x > max_val: __a = math.floor(val / multiple ) * multiple if x < min_val: __a = math.ceil(val / multiple ) * multiple return x __a = (output_size, output_size) if isinstance(_A , _A ) else output_size __a = get_image_size(_A ) __a = output_size # determine new height and width __a = output_height / input_height __a = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __a = scale_width else: # fit height __a = scale_height __a = constraint_to_multiple_of(scale_height * input_height , multiple=_A ) __a = constraint_to_multiple_of(scale_width * input_width , multiple=_A ) return (new_height, new_width) class __lowerCAmelCase ( lowerCamelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ['pixel_values'] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = False , _a = 1 , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , **_a , ): super().__init__(**__snake_case ) __a = size if size is not None else {'height': 384, 'width': 384} __a = get_size_dict(__snake_case ) __a = do_resize __a = size __a = keep_aspect_ratio __a = ensure_multiple_of __a = resample __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __a = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCAmelCase ( self , _a , _a , _a = False , _a = 1 , _a = PILImageResampling.BICUBIC , _a = None , **_a , ): __a = get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) __a = get_resize_output_image_size( __snake_case , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=__snake_case , multiple=__snake_case , ) return resize(__snake_case , size=__snake_case , resample=__snake_case , data_format=__snake_case , **__snake_case ) def __UpperCAmelCase ( self , _a , _a , _a = None , **_a , ): return rescale(__snake_case , scale=__snake_case , data_format=__snake_case , **__snake_case ) def __UpperCAmelCase ( self , _a , _a , _a , _a = None , **_a , ): return normalize(__snake_case , mean=__snake_case , std=__snake_case , data_format=__snake_case , **__snake_case ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(__snake_case ) __a = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __a = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __a = resample if resample is not None else self.resample __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = make_list_of_images(__snake_case ) if not valid_images(__snake_case ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __a = [to_numpy_array(__snake_case ) for image in images] if do_resize: __a = [self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) for image in images] if do_rescale: __a = [self.rescale(image=__snake_case , scale=__snake_case ) for image in images] if do_normalize: __a = [self.normalize(image=__snake_case , mean=__snake_case , std=__snake_case ) for image in images] __a = [to_channel_dimension_format(__snake_case , __snake_case ) for image in images] __a = {'pixel_values': images} return BatchFeature(data=__snake_case , tensor_type=__snake_case ) def __UpperCAmelCase ( self , _a , _a = None ): __a = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__snake_case ) != len(__snake_case ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(__snake_case ): __a = target_sizes.numpy() __a = [] for idx in range(len(__snake_case ) ): __a = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=__snake_case ) __a = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__snake_case ) else: __a = logits.argmax(dim=1 ) __a = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
357
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): self.assertEqual(len(_a ) , len(_a ) ) for a, b in zip(_a , _a ): self.assertAlmostEqual(_a , _a , delta=_a ) def __UpperCAmelCase ( self ): __a = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_a ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def __UpperCAmelCase ( self ): __a = None ops.enable_eager_execution_internal() __a = tf.config.list_physical_devices('''CPU''' ) if len(_a ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a = tf.config.list_logical_devices(device_type='''CPU''' ) __a = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a = GradientAccumulator() __a = tf.Variable([4.0, 3.0] ) __a , __a = create_optimizer(5E-5 , 10 , 5 ) __a = tf.Variable([0.0, 0.0] , trainable=_a ) def accumulate_on_replica(_a ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_a , _a ): with strategy.scope(): __a = strategy.experimental_local_results(_a ) local_variables[0].assign(_a ) local_variables[1].assign(_a ) strategy.run(_a , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_a ) def _check_local_values(_a , _a ): __a = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _a , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _a , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
11
0
"""simple docstring""" import re def lowercase ( lowerCAmelCase__ : int ) -> Optional[int]: if len(re.findall('''[ATCG]''' , lowerCAmelCase__ ) ) != len(lowerCAmelCase__ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''' , '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
358
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: lowercase_ = None lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json", "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json", }, } lowercase_ = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off lowercase_ = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = ['input_ids', 'attention_mask'] __UpperCAmelCase : Optional[Any] = MBartTokenizer __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , **_a , ) __a = vocab_file __a = False if not self.vocab_file else True __a = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __a = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __a = src_lang if src_lang is not None else '''en_XX''' __a = self.convert_tokens_to_ids(self._src_lang ) __a = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __UpperCAmelCase ( self ): return self._src_lang @src_lang.setter def __UpperCAmelCase ( self , _a ): __a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a , _a , _a , **_a ): if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __a = src_lang __a = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) __a = self.convert_tokens_to_ids(_a ) __a = tgt_lang_id return inputs def __UpperCAmelCase ( self , _a , _a = "en_XX" , _a = None , _a = "ro_RO" , **_a , ): __a = src_lang __a = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def __UpperCAmelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __UpperCAmelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a , _a = None ): 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(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return __a = 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 ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
11
0
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=3 , _a=True , _a=True , _a=0.1 , _a=0.1 , _a=224 , _a=1_000 , _a=[3, 3, 6, 4] , _a=[48, 56, 112, 220] , ): __a = parent __a = batch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = num_labels __a = image_size __a = layer_depths __a = embed_dims def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='''gelu''' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=a__ , layer_scale_init_value=1E-5 , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = SwiftFormerModel(config=a__ ) model.to(a__ ) model.eval() __a = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = self.num_labels __a = SwiftFormerForImageClassification(a__ ) model.to(a__ ) model.eval() __a = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) __a = SwiftFormerForImageClassification(a__ ) model.to(a__ ) model.eval() __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): ((__a) , (__a) , (__a)) = self.prepare_config_and_inputs() __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __a , __a , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Optional[int] = False def __UpperCAmelCase ( self ): __a = SwiftFormerModelTester(self ) __a = ConfigTester( self , config_class=a__ , has_text_modality=a__ , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(a__ ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(a__ ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def __UpperCAmelCase ( self ): for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = SwiftFormerModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @unittest.skip(reason='''SwiftFormer does not output attentions''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(a__ , a__ ) ) __a = outputs.hidden_states __a = 8 self.assertEqual(len(a__ ) , a__ ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(a__ ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(a__ , a__ , a__ ) def __UpperCAmelCase ( self ): def _config_zero_init(_a ): __a = copy.deepcopy(a__ ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(a__ , a__ , 1E-10 ) if isinstance(getattr(a__ , a__ , a__ ) , a__ ): __a = _config_zero_init(getattr(a__ , a__ ) ) setattr(a__ , a__ , a__ ) return configs_no_init __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = _config_zero_init(a__ ) for model_class in self.all_model_classes: __a = model_class(config=a__ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def lowercase ( ) -> str: __a = 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 ): return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): __a = SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(a__ ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=a__ , return_tensors='''pt''' ).to(a__ ) # forward pass with torch.no_grad(): __a = model(**a__ ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , a__ ) __a = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1E-4 ) )
359
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging 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.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn 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]\n" class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-question-answering''' ) self.tool.setup() __a = load_tool('''text-question-answering''' , remote=_a ) def __UpperCAmelCase ( self ): __a = self.tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' )
11
0
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> List[Any]: def get_masked_lm_array(lowerCAmelCase__ : str ): __a = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __a = tf.train.load_variable(lowerCAmelCase__ , lowerCAmelCase__ ) if "kernel" in name: __a = array.transpose() return torch.from_numpy(lowerCAmelCase__ ) def get_encoder_array(lowerCAmelCase__ : str ): __a = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __a = tf.train.load_variable(lowerCAmelCase__ , lowerCAmelCase__ ) if "kernel" in name: __a = array.transpose() return torch.from_numpy(lowerCAmelCase__ ) def get_encoder_layer_array(lowerCAmelCase__ : int , lowerCAmelCase__ : str ): __a = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __a = tf.train.load_variable(lowerCAmelCase__ , lowerCAmelCase__ ) if "kernel" in name: __a = array.transpose() return torch.from_numpy(lowerCAmelCase__ ) def get_encoder_attention_layer_array(lowerCAmelCase__ : int , lowerCAmelCase__ : str , lowerCAmelCase__ : Any ): __a = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __a = tf.train.load_variable(lowerCAmelCase__ , lowerCAmelCase__ ) __a = array.reshape(lowerCAmelCase__ ) if "kernel" in name: __a = array.transpose() return torch.from_numpy(lowerCAmelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) __a = BertConfig.from_json_file(lowerCAmelCase__ ) __a = BertForMaskedLM(lowerCAmelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): __a = model.bert.encoder.layer[layer_index] # Self-attention __a = layer.attention.self __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_query_dense/kernel''' , self_attn.query.weight.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_query_dense/bias''' , self_attn.query.bias.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_key_dense/kernel''' , self_attn.key.weight.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_key_dense/bias''' , self_attn.key.bias.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_value_dense/kernel''' , self_attn.value.weight.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_value_dense/bias''' , self_attn.value.bias.data.shape ) # Self-attention Output __a = layer.attention.output __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_output_dense/kernel''' , self_output.dense.weight.data.shape ) __a = get_encoder_attention_layer_array( lowerCAmelCase__ , '''_output_dense/bias''' , self_output.dense.bias.data.shape ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_attention_layer_norm/gamma''' ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_attention_layer_norm/beta''' ) # Intermediate __a = layer.intermediate __a = get_encoder_layer_array(lowerCAmelCase__ , '''_intermediate_dense/kernel''' ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_intermediate_dense/bias''' ) # Output __a = layer.output __a = get_encoder_layer_array(lowerCAmelCase__ , '''_output_dense/kernel''' ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_output_dense/bias''' ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_output_layer_norm/gamma''' ) __a = get_encoder_layer_array(lowerCAmelCase__ , '''_output_layer_norm/beta''' ) # Embeddings __a = get_encoder_array('''_position_embedding_layer/embeddings''' ) __a = get_encoder_array('''_type_embedding_layer/embeddings''' ) __a = get_encoder_array('''_embedding_norm_layer/gamma''' ) __a = get_encoder_array('''_embedding_norm_layer/beta''' ) # LM Head __a = model.cls.predictions.transform __a = get_masked_lm_array('''dense/kernel''' ) __a = get_masked_lm_array('''dense/bias''' ) __a = get_masked_lm_array('''layer_norm/gamma''' ) __a = get_masked_lm_array('''layer_norm/beta''' ) __a = get_masked_lm_array('''embedding_table''' ) # Pooling __a = BertPooler(config=lowerCAmelCase__ ) __a = get_encoder_array('''_pooler_layer/kernel''' ) __a = get_encoder_array('''_pooler_layer/bias''' ) # Export final model model.save_pretrained(lowerCAmelCase__ ) # Integration test - should load without any errors ;) __a = BertForMaskedLM.from_pretrained(lowerCAmelCase__ ) print(new_model.eval() ) print('''Model conversion was done sucessfully!''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path." ) parser.add_argument( "--bert_config_file", type=str, required=True, help="The config json file corresponding to the BERT model. This specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", type=str, required=True, help="Path to the output PyTorch model.", ) lowercase_ = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig", ], "processing_blip_2": ["Blip2Processor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Blip2Model", "Blip2QFormerModel", "Blip2PreTrainedModel", "Blip2ForConditionalGeneration", "Blip2VisionModel", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" 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() lowercase_ = logging.get_logger(__name__) lowercase_ = "https://openaipublic.azureedge.net/jukebox/models/" lowercase_ = { "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 lowercase ( lowerCAmelCase__ : List[Any] ) -> Optional[Any]: if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10: __a = key.replace('''.model.1.bias''' , '''.conv1d_1.bias''' ) elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10: __a = key.replace('''.model.1.weight''' , '''.conv1d_1.weight''' ) elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10: __a = key.replace('''.model.3.bias''' , '''.conv1d_2.bias''' ) elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10: __a = key.replace('''.model.3.weight''' , '''.conv1d_2.weight''' ) if "conditioner_blocks.0." in key: __a = key.replace('''conditioner_blocks.0''' , '''conditioner_blocks''' ) if "prime_prior" in key: __a = 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 = 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 = 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 lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any ) -> Tuple: __a = {} import re __a = re.compile(r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) __a = re.compile( r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) __a = re.compile(r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) __a = re.compile(r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) __a = re.compile( r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) __a = re.compile(r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) __a = re.compile(r'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' ) __a = re.compile( r'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) __a = 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(__snake_case ): __a = re_encoder_block_conv_in.match(__snake_case ) __a = regex_match.groups() __a = int(groups[2] ) * 2 + int(groups[3] ) __a = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' __a = re_encoder_block_conv_in.sub(__snake_case , __snake_case ) elif re_encoder_block_resnet.fullmatch(__snake_case ): __a = re_encoder_block_resnet.match(__snake_case ) __a = regex_match.groups() __a = int(groups[2] ) * 2 + int(groups[3] ) __a = {'''1''': 1, '''3''': 2}[groups[-2]] __a = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' __a = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' __a = prefix + resnet_block __a = re_encoder_block_resnet.sub(__snake_case , __snake_case ) elif re_encoder_block_proj_out.fullmatch(__snake_case ): __a = re_encoder_block_proj_out.match(__snake_case ) __a = regex_match.groups() __a = f'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' __a = re_encoder_block_proj_out.sub(__snake_case , __snake_case ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(__snake_case ): __a = re_decoder_block_conv_out.match(__snake_case ) __a = regex_match.groups() __a = int(groups[2] ) * 2 + int(groups[3] ) - 2 __a = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' __a = re_decoder_block_conv_out.sub(__snake_case , __snake_case ) elif re_decoder_block_resnet.fullmatch(__snake_case ): __a = re_decoder_block_resnet.match(__snake_case ) __a = regex_match.groups() __a = int(groups[2] ) * 2 + int(groups[3] ) - 2 __a = {'''1''': 1, '''3''': 2}[groups[-2]] __a = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' __a = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' __a = prefix + resnet_block __a = re_decoder_block_resnet.sub(__snake_case , __snake_case ) elif re_decoder_block_proj_in.fullmatch(__snake_case ): __a = re_decoder_block_proj_in.match(__snake_case ) __a = regex_match.groups() __a = f'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' __a = re_decoder_block_proj_in.sub(__snake_case , __snake_case ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(__snake_case ): __a = re_prior_cond_conv_out.match(__snake_case ) __a = regex_match.groups() __a = int(groups[1] ) * 2 + int(groups[2] ) - 2 __a = f'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' __a = re_prior_cond_conv_out.sub(__snake_case , __snake_case ) elif re_prior_cond_resnet.fullmatch(__snake_case ): __a = re_prior_cond_resnet.match(__snake_case ) __a = regex_match.groups() __a = int(groups[1] ) * 2 + int(groups[2] ) - 2 __a = {'''1''': 1, '''3''': 2}[groups[-2]] __a = f'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' __a = f'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' __a = prefix + resnet_block __a = re_prior_cond_resnet.sub(__snake_case , __snake_case ) elif re_prior_cond_proj_in.fullmatch(__snake_case ): __a = re_prior_cond_proj_in.match(__snake_case ) __a = regex_match.groups() __a = f'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' __a = re_prior_cond_proj_in.sub(__snake_case , __snake_case ) # keep original key else: __a = original_key __a = replace_key(__snake_case ) 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 = model_state_dict[f'''{key_prefix}.{key}'''] print(f'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) __a = original_key __a = original_key __a = value return new_dict @torch.no_grad() def lowercase ( lowerCAmelCase__ : str=None , lowerCAmelCase__ : List[str]=None ) -> Optional[Any]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f'''{pytorch_dump_folder_path}/{file.split('/' )[-1]}''' ): __a = requests.get(f'''{PREFIX}{file}''' , allow_redirects=__snake_case ) os.makedirs(f'''{pytorch_dump_folder_path}/''' , exist_ok=__snake_case ) open(f'''{pytorch_dump_folder_path}/{file.split('/' )[-1]}''' , '''wb''' ).write(r.content ) __a = MODEL_MAPPING[model_name.split('''/''' )[-1]] __a = JukeboxConfig.from_pretrained(__snake_case ) __a = JukeboxModel(__snake_case ) __a = [] __a = {} for i, dict_name in enumerate(__snake_case ): __a = torch.load(f'''{pytorch_dump_folder_path}/{dict_name.split('/' )[-1]}''' )['''model'''] __a = {} for k in old_dic.keys(): if k.endswith('''.b''' ): __a = old_dic[k] elif k.endswith('''.w''' ): __a = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: __a = old_dic[k] else: __a = old_dic[k] __a = '''vqvae''' if i == 0 else f'''priors.{3 - i}''' __a = fix_jukebox_keys(__snake_case , model.state_dict() , __snake_case , __snake_case ) weight_dict.append(__snake_case ) __a = weight_dict.pop(0 ) model.vqvae.load_state_dict(__snake_case ) for i in range(len(__snake_case ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(__snake_case ).mkdir(exist_ok=__snake_case ) with open(f'''{pytorch_dump_folder_path}/mapping.json''' , '''w''' ) as txtfile: json.dump(__snake_case , __snake_case ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__snake_case ) return weight_dict if __name__ == "__main__": lowercase_ = 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.", ) lowercase_ = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
361
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a = len(lowerCAmelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCAmelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCAmelCase__ , lowerCAmelCase__ , ) def lowercase ( lowerCAmelCase__ : int ) -> None: __a = [] depth_first_search([] , [] , [] , lowerCAmelCase__ , lowerCAmelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCAmelCase__ ) print('''''' ) print(len(lowerCAmelCase__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
11
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=_snake_case ) class __lowerCAmelCase ( _snake_case ): '''simple docstring''' __UpperCAmelCase : List[Any] = field(default='audio-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) __UpperCAmelCase : Optional[Any] = Features({'audio': Audio()} ) __UpperCAmelCase : int = Features({'labels': ClassLabel} ) __UpperCAmelCase : Tuple = 'audio' __UpperCAmelCase : Dict = 'labels' def __UpperCAmelCase ( self , _a ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , UpperCamelCase__ ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __a = copy.deepcopy(self ) __a = self.label_schema.copy() __a = features[self.label_column] __a = label_schema return task_template @property def __UpperCAmelCase ( self ): return { self.audio_column: "audio", self.label_column: "labels", }
362
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
11
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( snake_case__ ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_A ) model.to(_A ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_A ) model.to(_A ) model.eval() __a = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_A ) model.to(_A ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Dict = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Dict = False __UpperCAmelCase : Any = False __UpperCAmelCase : Tuple = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_A , has_text_modality=_A ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_A ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_A , _A ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_A ) , _A ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_A , _A , _A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def lowercase ( ) -> Optional[int]: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _A ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_A , return_tensors='''pt''' ).to(_A ) # forward pass with torch.no_grad(): __a = model(**_A ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _A ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_A ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_A , return_tensors='''pt''' ).to(_A ) # forward pass with torch.no_grad(): __a = model(**_A ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _A ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _A , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_A ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_A , return_tensors='''pt''' ).to(_A ) # forward pass with torch.no_grad(): __a = model(**_A ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_A , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _A ) __a = image_processor.post_process_semantic_segmentation(outputs=_A ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _A )
363
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = 'vit_mae' def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=True , _a=16 , _a=512 , _a=8 , _a=2_048 , _a=0.75 , _a=False , **_a , ): super().__init__(**_a ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = decoder_num_attention_heads __a = decoder_hidden_size __a = decoder_num_hidden_layers __a = decoder_intermediate_size __a = mask_ratio __a = norm_pix_loss
11
0
"""simple docstring""" from collections.abc import Sequence def lowercase ( lowerCAmelCase__ : Sequence[float] , lowerCAmelCase__ : bool = False ) -> float: if not arr: return 0 __a = 0 if allow_empty_subarrays else float('''-inf''' ) __a = 0.0 for num in arr: __a = max(0 if allow_empty_subarrays else num , curr_sum + num ) __a = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() __lowerCAmelCase = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'''{max_subarray_sum(nums) = }''')
364
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Optional[int] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
11
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel 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, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = CycleDiffusionPipeline __UpperCAmelCase : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { 'negative_prompt', 'height', 'width', 'negative_prompt_embeds', } __UpperCAmelCase : Optional[int] = PipelineTesterMixin.required_optional_params - {'latents'} __UpperCAmelCase : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'} ) __UpperCAmelCase : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase : List[Any] = 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''') , cross_attention_dim=32 , ) __a = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , num_train_timesteps=1_000 , clip_sample=_a , set_alpha_to_one=_a , ) 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 , ) 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=1_000 , ) __a = CLIPTextModel(_a ) __a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __UpperCAmelCase ( self , _a , _a=0 ): __a = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) __a = image / 2 + 0.5 if str(_a ).startswith('''mps''' ): __a = torch.manual_seed(_a ) else: __a = torch.Generator(device=_a ).manual_seed(_a ) __a = { '''prompt''': '''An astronaut riding an elephant''', '''source_prompt''': '''An astronaut riding a horse''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''eta''': 0.1, '''strength''': 0.8, '''guidance_scale''': 3, '''source_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def __UpperCAmelCase ( self ): __a = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = CycleDiffusionPipeline(**_a ) __a = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = pipe(**_a ) __a = output.images __a = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __a = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def __UpperCAmelCase ( self ): __a = self.get_dummy_components() for name, module in components.items(): if hasattr(_a , '''half''' ): __a = module.half() __a = CycleDiffusionPipeline(**_a ) __a = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = pipe(**_a ) __a = output.images __a = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __a = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def __UpperCAmelCase ( self ): return super().test_save_load_local() @unittest.skip('''non-deterministic pipeline''' ) def __UpperCAmelCase ( self ): return super().test_inference_batch_single_identical() @skip_mps def __UpperCAmelCase ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCAmelCase ( self ): return super().test_save_load_optional_components() @skip_mps def __UpperCAmelCase ( self ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) __a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy''' ) __a = init_image.resize((512, 512) ) __a = '''CompVis/stable-diffusion-v1-4''' __a = DDIMScheduler.from_pretrained(_a , subfolder='''scheduler''' ) __a = CycleDiffusionPipeline.from_pretrained( _a , scheduler=_a , safety_checker=_a , torch_dtype=torch.floataa , revision='''fp16''' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() __a = '''A black colored car''' __a = '''A blue colored car''' __a = torch.manual_seed(0 ) __a = pipe( prompt=_a , source_prompt=_a , image=_a , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_a , output_type='''np''' , ) __a = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5E-1 def __UpperCAmelCase ( self ): __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) __a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy''' ) __a = init_image.resize((512, 512) ) __a = '''CompVis/stable-diffusion-v1-4''' __a = DDIMScheduler.from_pretrained(_a , subfolder='''scheduler''' ) __a = CycleDiffusionPipeline.from_pretrained(_a , scheduler=_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() __a = '''A black colored car''' __a = '''A blue colored car''' __a = torch.manual_seed(0 ) __a = pipe( prompt=_a , source_prompt=_a , image=_a , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_a , output_type='''np''' , ) __a = output.images assert np.abs(image - expected_image ).max() < 2E-2
365
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
11
0
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowercase_ = random.Random() def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any]=1.0 , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : int=None ) -> str: if rng is None: __a = global_rng __a = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=7 , _a=400 , _a=2_000 , _a=10 , _a=160 , _a=8 , _a=0.0 , _a=4_000 , _a=False , _a=True , ): __a = parent __a = batch_size __a = min_seq_length __a = max_seq_length __a = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __a = padding_value __a = sampling_rate __a = return_attention_mask __a = do_normalize __a = feature_size __a = chunk_length __a = hop_length def __UpperCAmelCase ( self ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCAmelCase ( self , _a=False , _a=False ): def _flatten(_a ): return list(itertools.chain(*__lowercase ) ) if equal_length: __a = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __a = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __a = [np.asarray(__lowercase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def __UpperCAmelCase ( self ): __a = WhisperFeatureExtractionTester(self ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __a = feat_extract_first.save_pretrained(__lowercase )[0] check_json_file_has_correct_format(__lowercase ) __a = self.feature_extraction_class.from_pretrained(__lowercase ) __a = feat_extract_first.to_dict() __a = feat_extract_second.to_dict() __a = feat_extract_first.mel_filters __a = feat_extract_second.mel_filters self.assertTrue(np.allclose(__lowercase , __lowercase ) ) self.assertEqual(__lowercase , __lowercase ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __a = os.path.join(__lowercase , '''feat_extract.json''' ) feat_extract_first.to_json_file(__lowercase ) __a = self.feature_extraction_class.from_json_file(__lowercase ) __a = feat_extract_first.to_dict() __a = feat_extract_second.to_dict() __a = feat_extract_first.mel_filters __a = feat_extract_second.mel_filters self.assertTrue(np.allclose(__lowercase , __lowercase ) ) self.assertEqual(__lowercase , __lowercase ) def __UpperCAmelCase ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus __a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __a = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __a = [np.asarray(__lowercase ) for speech_input in speech_inputs] # Test feature size __a = feature_extractor(__lowercase , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __a = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features __a = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1E-3 ) ) # Test batched __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ): self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __a = [floats_list((1, x) )[0] for x in (800, 800, 800)] __a = np.asarray(__lowercase ) __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ): self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1E-3 ) ) # Test truncation required __a = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __a = [np.asarray(__lowercase ) for speech_input in speech_inputs] __a = [x[: feature_extractor.n_samples] for x in speech_inputs] __a = [np.asarray(__lowercase ) for speech_input in speech_inputs_truncated] __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features __a = feature_extractor(__lowercase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ): self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1E-3 ) ) def __UpperCAmelCase ( self ): import torch __a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a = np.random.rand(100 , 32 ).astype(np.floataa ) __a = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __a = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __a = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __UpperCAmelCase ( self , _a ): __a = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech __a = ds.sort('''id''' ).select(range(__lowercase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __UpperCAmelCase ( self ): # fmt: off __a = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __a = self._load_datasamples(1 ) __a = WhisperFeatureExtractor() __a = feature_extractor(__lowercase , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __lowercase , atol=1E-4 ) ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a = self._load_datasamples(1 )[0] __a = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __a = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__lowercase )[0] self.assertTrue(np.all(np.mean(__lowercase ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__lowercase ) - 1 ) < 1E-3 ) )
366
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'rwkv' __UpperCAmelCase : Optional[Any] = {'max_position_embeddings': 'context_length'} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): __a = vocab_size __a = context_length __a = hidden_size __a = num_hidden_layers __a = attention_hidden_size if attention_hidden_size is not None else hidden_size __a = intermediate_size if intermediate_size is not None else 4 * hidden_size __a = layer_norm_epsilon __a = rescale_every __a = use_cache __a = bos_token_id __a = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
11
0
"""simple docstring""" import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Union[str, Any] = None def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_dict ) __a = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __a ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __a = os.path.join(__a , '''feat_extract.json''' ) feat_extract_first.to_json_file(__a ) __a = self.feature_extraction_class.from_json_file(__a ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __a = feat_extract_first.save_pretrained(__a )[0] check_json_file_has_correct_format(__a ) __a = self.feature_extraction_class.from_pretrained(__a ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def __UpperCAmelCase ( self ): __a = self.feature_extraction_class() self.assertIsNotNone(__a )
367
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = (UnCLIPScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCAmelCase ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_a , prev_timestep=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''fixed_small_log''' ) __a = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''learned_range''' ) __a = scheduler_class(**_a ) __a = 0.5 assert scheduler._get_variance(1 , predicted_variance=_a ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_a ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_a ) - -0.001_0011 < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(25 ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) if i + 1 == timesteps.shape[0]: __a = None else: __a = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a = scheduler.step( _a , _a , _a , prev_timestep=_a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass
11
0
from __future__ import annotations class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = data __a = None __a = None def lowercase ( lowerCAmelCase__ : Tuple ) -> None: # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowercase ( lowerCAmelCase__ : str ) -> int: return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowercase ( lowerCAmelCase__ : str ) -> bool: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowercase ( ) -> None: # Main function for testing. __a = Node(1 ) __a = Node(2 ) __a = Node(3 ) __a = Node(4 ) __a = Node(5 ) __a = Node(6 ) __a = Node(7 ) __a = Node(8 ) __a = Node(9 ) print(is_full_binary_tree(lowerCAmelCase_ ) ) print(depth_of_tree(lowerCAmelCase_ ) ) print('''Tree is: ''' ) display(lowerCAmelCase_ ) if __name__ == "__main__": main()
368
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
11
0
"""simple docstring""" import sys import turtle def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(__SCREAMING_SNAKE_CASE , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , depth - 1 ) triangle(__SCREAMING_SNAKE_CASE , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , depth - 1 ) triangle(__SCREAMING_SNAKE_CASE , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , get_mid(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) lowercase_ = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") lowercase_ = [(-1_7_5, -1_2_5), (0, 1_7_5), (1_7_5, -1_2_5)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
369
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
0
import glob import os import random from string import ascii_lowercase, digits import cva lowercase_ = '''''' lowercase_ = '''''' lowercase_ = '''''' lowercase_ = 1 # (0 is vertical, 1 is horizontal) def lowercase ( ) -> Union[str, Any]: __a , __a = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __a , __a , __a = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __a = random_chars(32 ) __a = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __a = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __a = [] for anno in new_annos[index]: __a = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> Union[str, Any]: __a = [] __a = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __a = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __a = in_file.readlines() __a = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __a = [] for obj_list in obj_lists: __a = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int = 1 ) -> Optional[int]: __a = [] __a = [] __a = [] for idx in range(len(__lowerCAmelCase ) ): __a = [] __a = img_list[idx] path_list.append(__lowerCAmelCase ) __a = anno_list[idx] __a = cva.imread(__lowerCAmelCase ) if flip_type == 1: __a = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __a = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __a = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __a = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def lowercase ( lowerCAmelCase__ : int = 32 ) -> Any: assert number_char > 1, "The number of character should greater than 1" __a = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
370
"""simple docstring""" from math import factorial, radians def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 18 , lowerCAmelCase__ : int = 10 ) -> float: __a = angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians __a = radians(lowerCAmelCase__ ) __a = angle_in_radians __a = 3 __a = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) __a = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__("doctest").testmod()
11
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class __lowerCAmelCase ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = "trajectory_transformer" __UpperCAmelCase : Union[str, Any] = ["past_key_values"] __UpperCAmelCase : int = { "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , _a=100 , _a=5 , _a=1 , _a=1 , _a=249 , _a=6 , _a=17 , _a=25 , _a=4 , _a=4 , _a=128 , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0006 , _a=512 , _a=0.02 , _a=1E-12 , _a=1 , _a=True , _a=1 , _a=50_256 , _a=50_256 , **_a , ): __a = vocab_size __a = action_weight __a = reward_weight __a = value_weight __a = max_position_embeddings __a = block_size __a = action_dim __a = observation_dim __a = transition_dim __a = learning_rate __a = n_layer __a = n_head __a = n_embd __a = embd_pdrop __a = attn_pdrop __a = resid_pdrop __a = initializer_range __a = layer_norm_eps __a = kaiming_initializer_range __a = use_cache super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ )
371
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : dict ) -> tuple: return (data["data"], data["target"]) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ) -> np.ndarray: __a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowerCAmelCase__ , lowerCAmelCase__ ) # Predict target for test data __a = xgb.predict(lowerCAmelCase__ ) __a = predictions.reshape(len(lowerCAmelCase__ ) , 1 ) return predictions def lowercase ( ) -> None: __a = fetch_california_housing() __a , __a = data_handling(lowerCAmelCase__ ) __a , __a , __a , __a = train_test_split( lowerCAmelCase__ , lowerCAmelCase__ , test_size=0.25 , random_state=1 ) __a = xgboost(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
11
0
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
351
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'funnel' __UpperCAmelCase : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', } def __init__( self , _a=30_522 , _a=[4, 4, 4] , _a=None , _a=2 , _a=768 , _a=12 , _a=64 , _a=3_072 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=None , _a=1E-9 , _a="mean" , _a="relative_shift" , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = block_sizes __a = [1] * len(_a ) if block_repeats is None else block_repeats assert len(_a ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __a = num_decoder_layers __a = d_model __a = n_head __a = d_head __a = d_inner __a = hidden_act __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = initializer_range __a = initializer_std __a = layer_norm_eps assert pooling_type in [ "mean", "max", ], f'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' __a = pooling_type assert attention_type in [ "relative_shift", "factorized", ], f'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' __a = attention_type __a = separate_cls __a = truncate_seq __a = pool_q_only super().__init__(**_a ) @property def __UpperCAmelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.''' ) @property def __UpperCAmelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError('''This model does not support the setting of `num_blocks`. Please set `block_sizes`.''' )
11
0
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" lowercase_ = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" lowercase_ = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=None , _a=None , _a=None , _a="auto" , _a=-1 , _a=0.9 , _a=5 , _a=500 , _a="gpt2-large" , _a=-1 , _a=1_024 , _a=25 , _a=5 , _a=True , _a=25 , ): __a = compute_mauve( p_text=_a , q_text=_a , p_features=_a , q_features=_a , p_tokens=_a , q_tokens=_a , num_buckets=_a , pca_max_data=_a , kmeans_explained_var=_a , kmeans_num_redo=_a , kmeans_max_iter=_a , featurize_model_name=_a , device_id=_a , max_text_length=_a , divergence_curve_discretization_size=_a , mauve_scaling_factor=_a , verbose=_a , seed=_a , ) return out
352
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> str: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _a ) __a = image_processor.post_process_semantic_segmentation(outputs=_a ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _a )
11
0
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): warnings.warn( '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use BeitImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
353
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
11
0
"""simple docstring""" from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
354
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __UpperCAmelCase ( self , _a , _a=None , _a="This is a sound of {}." ): if isinstance(_a , _a ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(_a ).content else: with open(_a , '''rb''' ) as f: __a = f.read() if isinstance(_a , _a ): __a = ffmpeg_read(_a , self.feature_extractor.sampling_rate ) if not isinstance(_a , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) __a = candidate_labels __a = [hypothesis_template.format(_a ) for x in candidate_labels] __a = self.tokenizer(_a , return_tensors=self.framework , padding=_a ) __a = [text_inputs] return inputs def __UpperCAmelCase ( self , _a ): __a = model_inputs.pop('''candidate_labels''' ) __a = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _a ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**_a , **_a ) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.pop('''candidate_labels''' ) __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_a , _a ) , key=lambda _a : -x[0] ) ] return result
11
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int = 600851475143 ) -> int: try: __a = int(lowerCAmelCase__ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) __a = 1 __a = 2 while i * i <= n: while n % i == 0: __a = i n //= i i += 1 if n > 1: __a = n return int(lowerCAmelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
355
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
11
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "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 __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'xlm' __UpperCAmelCase : int = { 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self , _a=30_145 , _a=2_048 , _a=12 , _a=16 , _a=0.1 , _a=0.1 , _a=True , _a=False , _a=False , _a=False , _a=1 , _a=True , _a=512 , _a=2_048**-0.5 , _a=1E-12 , _a=0.02 , _a=0 , _a=1 , _a=2 , _a=3 , _a=5 , _a=True , _a="first" , _a=True , _a=None , _a=True , _a=0.1 , _a=5 , _a=5 , _a=0 , _a=0 , _a=2 , _a=0 , **_a , ): __a = vocab_size __a = emb_dim __a = n_layers __a = n_heads __a = dropout __a = attention_dropout __a = gelu_activation __a = sinusoidal_embeddings __a = causal __a = asm __a = n_langs __a = use_lang_emb __a = layer_norm_eps __a = bos_index __a = eos_index __a = pad_index __a = unk_index __a = mask_index __a = is_encoder __a = max_position_embeddings __a = embed_init_std __a = init_std __a = summary_type __a = summary_use_proj __a = summary_activation __a = summary_proj_to_labels __a = summary_first_dropout __a = start_n_top __a = end_n_top __a = mask_token_id __a = lang_id if "n_words" in kwargs: __a = kwargs['''n_words'''] super().__init__(pad_token_id=_a , bos_token_id=_a , **_a ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
356
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" import socket def lowercase ( ) -> Dict: __a = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) __a = socket.gethostname() __a = 12312 sock.connect((host, port) ) sock.send(b'''Hello server!''' ) with open('''Received_file''' , '''wb''' ) as out_file: print('''File opened''' ) print('''Receiving data...''' ) while True: __a = sock.recv(1024 ) if not data: break out_file.write(lowerCAmelCase__ ) print('''Successfully received the file''' ) sock.close() print('''Connection closed''' ) if __name__ == "__main__": main()
357
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): self.assertEqual(len(_a ) , len(_a ) ) for a, b in zip(_a , _a ): self.assertAlmostEqual(_a , _a , delta=_a ) def __UpperCAmelCase ( self ): __a = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_a ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def __UpperCAmelCase ( self ): __a = None ops.enable_eager_execution_internal() __a = tf.config.list_physical_devices('''CPU''' ) if len(_a ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a = tf.config.list_logical_devices(device_type='''CPU''' ) __a = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a = GradientAccumulator() __a = tf.Variable([4.0, 3.0] ) __a , __a = create_optimizer(5E-5 , 10 , 5 ) __a = tf.Variable([0.0, 0.0] , trainable=_a ) def accumulate_on_replica(_a ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_a , _a ): with strategy.scope(): __a = strategy.experimental_local_results(_a ) local_variables[0].assign(_a ) local_variables[1].assign(_a ) strategy.run(_a , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_a ) def _check_local_values(_a , _a ): __a = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _a , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _a , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
11
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Optional[int] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
358
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: lowercase_ = None lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json", "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json", }, } lowercase_ = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off lowercase_ = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = ['input_ids', 'attention_mask'] __UpperCAmelCase : Optional[Any] = MBartTokenizer __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , **_a , ) __a = vocab_file __a = False if not self.vocab_file else True __a = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __a = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __a = src_lang if src_lang is not None else '''en_XX''' __a = self.convert_tokens_to_ids(self._src_lang ) __a = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __UpperCAmelCase ( self ): return self._src_lang @src_lang.setter def __UpperCAmelCase ( self , _a ): __a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a , _a , _a , **_a ): if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __a = src_lang __a = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) __a = self.convert_tokens_to_ids(_a ) __a = tgt_lang_id return inputs def __UpperCAmelCase ( self , _a , _a = "en_XX" , _a = None , _a = "ro_RO" , **_a , ): __a = src_lang __a = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def __UpperCAmelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __UpperCAmelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a ): __a = self.convert_tokens_to_ids(_a ) __a = [] __a = [self.eos_token_id, self.cur_lang_code] __a = self.convert_ids_to_tokens(self.prefix_tokens ) __a = self.convert_ids_to_tokens(self.suffix_tokens ) __a = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCAmelCase ( self , _a , _a = None ): 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(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return __a = 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 ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
11
0
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar lowercase_ = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): '''simple docstring''' __UpperCAmelCase : deque[T] # Cache store of keys __UpperCAmelCase : set[T] # References of the keys in cache __UpperCAmelCase : int = 1_0 # Maximum capacity of cache def __init__( self , _a ): __a = deque() __a = set() if not n: __a = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: __a = n def __UpperCAmelCase ( self , _a ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: __a = self.dq_store.pop() self.key_reference.remove(_a ) else: self.dq_store.remove(_a ) self.dq_store.appendleft(_a ) self.key_reference.add(_a ) def __UpperCAmelCase ( self ): for k in self.dq_store: print(_a ) def __repr__( self ): return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
359
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging 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.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn 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]\n" class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-question-answering''' ) self.tool.setup() __a = load_tool('''text-question-answering''' , remote=_a ) def __UpperCAmelCase ( self ): __a = self.tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' )
11
0
lowercase_ = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig", ], "processing_blip_2": ["Blip2Processor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Blip2Model", "Blip2QFormerModel", "Blip2PreTrainedModel", "Blip2ForConditionalGeneration", "Blip2VisionModel", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ['pixel_values'] def __init__( self , _a = True , _a = 1 / 255 , _a = True , _a = 8 , **_a , ): super().__init__(**_a ) __a = do_rescale __a = rescale_factor __a = do_pad __a = pad_size def __UpperCAmelCase ( self , _a , _a , _a = None , **_a ): return rescale(_a , scale=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a , _a = None ): __a , __a = get_image_size(_a ) __a = (old_height // size + 1) * size - old_height __a = (old_width // size + 1) * size - old_width return pad(_a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=_a ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_pad if do_pad is not None else self.do_pad __a = pad_size if pad_size is not None else self.pad_size __a = 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_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. __a = [to_numpy_array(_a ) for image in images] if do_rescale: __a = [self.rescale(image=_a , scale=_a ) for image in images] if do_pad: __a = [self.pad(_a , size=_a ) for image in images] __a = [to_channel_dimension_format(_a , _a ) for image in images] __a = {'''pixel_values''': images} return BatchFeature(data=_a , tensor_type=_a )
361
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a = len(lowerCAmelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCAmelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCAmelCase__ , lowerCAmelCase__ , ) def lowercase ( lowerCAmelCase__ : int ) -> None: __a = [] depth_first_search([] , [] , [] , lowerCAmelCase__ , lowerCAmelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCAmelCase__ ) print('''''' ) print(len(lowerCAmelCase__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
11
0
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)] ) def __UpperCAmelCase ( self , _a ): __a = GenerationConfig( do_sample=_a , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_a , config_name=_a ) __a = GenerationConfig.from_pretrained(_a , config_name=_a ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _a ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , _a ) def __UpperCAmelCase ( self ): __a = AutoConfig.from_pretrained('''gpt2''' ) __a = GenerationConfig.from_model_config(_a ) __a = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_a , _a ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def __UpperCAmelCase ( self ): __a = GenerationConfig() __a = { '''max_new_tokens''': 1_024, '''foo''': '''bar''', } __a = copy.deepcopy(_a ) __a = generation_config.update(**_a ) # update_kwargs was not modified (no side effects) self.assertEqual(_a , _a ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1_024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_a , {'''foo''': '''bar'''} ) def __UpperCAmelCase ( self ): __a = GenerationConfig() __a = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(_a ) __a = GenerationConfig.from_pretrained(_a ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) __a = GenerationConfig.from_model_config(_a ) assert not hasattr(_a , '''foo''' ) # no new kwargs should be initialized if from config def __UpperCAmelCase ( self ): __a = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , _a ) self.assertEqual(default_config.num_beams , 1 ) __a = GenerationConfig( do_sample=_a , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , _a ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_a ) __a = GenerationConfig.from_pretrained(_a , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , _a ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __UpperCAmelCase ( cls ): __a = TOKEN HfFolder.save_token(_a ) @classmethod def __UpperCAmelCase ( cls ): try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def __UpperCAmelCase ( self ): __a = GenerationConfig( do_sample=_a , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _a , repo_id='''test-generation-config''' , push_to_hub=_a , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_a , getattr(_a , _a ) ) def __UpperCAmelCase ( self ): __a = GenerationConfig( do_sample=_a , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _a , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=_a , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_a , getattr(_a , _a ) )
362
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
11
0
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
363
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = 'vit_mae' def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=True , _a=16 , _a=512 , _a=8 , _a=2_048 , _a=0.75 , _a=False , **_a , ): super().__init__(**_a ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = decoder_num_attention_heads __a = decoder_hidden_size __a = decoder_num_hidden_layers __a = decoder_intermediate_size __a = mask_ratio __a = norm_pix_loss
11
0
"""simple docstring""" class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): # we need a list not a string, so do something to change the type __a = arr.split(''',''' ) def __UpperCAmelCase ( self ): __a = [int(self.array[0] )] * len(self.array ) __a = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): __a = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) __a = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": __lowerCAmelCase = input("please input some numbers:") __lowerCAmelCase = SubArray(whole_array) __lowerCAmelCase = array.solve_sub_array() print(("the results is:", re))
364
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Optional[int] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
11
0
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ = "platform" import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] = PegasusConfig __UpperCAmelCase : Dict = {} __UpperCAmelCase : str = 'gelu' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = eos_token_id __a = pad_token_id __a = bos_token_id def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __a = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __a = np.concatenate([input_ids, eos_tensor] , axis=1 ) __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = 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 = prepare_pegasus_inputs_dict(_a , _a , _a ) return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict['''input_ids'''] ) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , _a , decoder_attention_mask=_a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_a , ) __a = model.decode(_a , _a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict['''input_ids'''] ) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , _a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_a , decoder_position_ids=_a , ) __a = model.decode(_a , _a , decoder_attention_mask=_a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]=None , lowerCAmelCase__ : Optional[int]=None , ) -> str: if attention_mask is None: __a = np.not_equal(lowerCAmelCase__ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __a = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __UpperCAmelCase : Optional[Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = FlaxPegasusModelTester(self ) __a = ConfigTester(self , config_class=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_a , _a , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_a , _a , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = self._prepare_for_class(_a , _a ) __a = model_class(_a ) @jax.jit def encode_jitted(_a , _a=None , **_a ): return model.encode(input_ids=_a , attention_mask=_a ) with self.subTest('''JIT Enabled''' ): __a = encode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = encode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = model_class(_a ) __a = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __a = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_a , _a , _a ): return model.decode( decoder_input_ids=_a , decoder_attention_mask=_a , encoder_outputs=_a , ) with self.subTest('''JIT Enabled''' ): __a = decode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = decode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __UpperCAmelCase ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''google/pegasus-large''' , from_pt=_a ) __a = np.ones((1, 1) ) __a = model(_a ) self.assertIsNotNone(_a ) @slow def __UpperCAmelCase ( self ): __a = FlaxPegasusForConditionalGeneration.from_pretrained('''google/pegasus-xsum''' ) __a = PegasusTokenizer.from_pretrained('''google/pegasus-xsum''' ) __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 turned off power to hundreds of thousands of customers.''', '''Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.''', ] __a = tokenizer(_a , return_tensors='''np''' , truncation=_a , max_length=512 , padding=_a ) __a = model.generate(**_a , num_beams=2 ).sequences __a = tokenizer.batch_decode(_a , skip_special_tokens=_a ) assert tgt_text == decoded
365
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
11
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/vocab.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/vocab.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/vocab.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/vocab.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/vocab.json", }, "merges_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/merges.txt", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/merges.txt", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/merges.txt", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/merges.txt", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/merges.txt", }, "tokenizer_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/tokenizer.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/tokenizer.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/tokenizer.json", }, } lowercase_ = { "gpt2": 1_0_2_4, "gpt2-medium": 1_0_2_4, "gpt2-large": 1_0_2_4, "gpt2-xl": 1_0_2_4, "distilgpt2": 1_0_2_4, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] __UpperCAmelCase : Optional[int] = GPTaTokenizer def __init__( self , _a=None , _a=None , _a=None , _a="<|endoftext|>" , _a="<|endoftext|>" , _a="<|endoftext|>" , _a=False , **_a , ): super().__init__( _a , _a , tokenizer_file=_a , unk_token=_a , bos_token=_a , eos_token=_a , add_prefix_space=_a , **_a , ) __a = kwargs.pop('''add_bos_token''' , _a ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _a ) != add_prefix_space: __a = getattr(_a , pre_tok_state.pop('''type''' ) ) __a = add_prefix_space __a = pre_tok_class(**_a ) __a = add_prefix_space def __UpperCAmelCase ( self , *_a , **_a ): __a = kwargs.get('''is_split_into_words''' , _a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): __a = kwargs.get('''is_split_into_words''' , _a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*_a , **_a ) def __UpperCAmelCase ( self , _a , _a = None ): __a = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def __UpperCAmelCase ( self , _a ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_a , add_special_tokens=_a ) + [self.eos_token_id] ) if len(_a ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
366
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'rwkv' __UpperCAmelCase : Optional[Any] = {'max_position_embeddings': 'context_length'} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): __a = vocab_size __a = context_length __a = hidden_size __a = num_hidden_layers __a = attention_hidden_size if attention_hidden_size is not None else hidden_size __a = intermediate_size if intermediate_size is not None else 4 * hidden_size __a = layer_norm_epsilon __a = rescale_every __a = use_cache __a = bos_token_id __a = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
11
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraOnnxConfig"], "tokenization_electra": ["ElectraTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["ElectraTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "ElectraForCausalLM", "ElectraForMaskedLM", "ElectraForMultipleChoice", "ElectraForPreTraining", "ElectraForQuestionAnswering", "ElectraForSequenceClassification", "ElectraForTokenClassification", "ElectraModel", "ElectraPreTrainedModel", "load_tf_weights_in_electra", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFElectraForMaskedLM", "TFElectraForMultipleChoice", "TFElectraForPreTraining", "TFElectraForQuestionAnswering", "TFElectraForSequenceClassification", "TFElectraForTokenClassification", "TFElectraModel", "TFElectraPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxElectraForCausalLM", "FlaxElectraForMaskedLM", "FlaxElectraForMultipleChoice", "FlaxElectraForPreTraining", "FlaxElectraForQuestionAnswering", "FlaxElectraForSequenceClassification", "FlaxElectraForTokenClassification", "FlaxElectraModel", "FlaxElectraPreTrainedModel", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
367
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = (UnCLIPScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCAmelCase ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_a , prev_timestep=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''fixed_small_log''' ) __a = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''learned_range''' ) __a = scheduler_class(**_a ) __a = 0.5 assert scheduler._get_variance(1 , predicted_variance=_a ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_a ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_a ) - -0.001_0011 < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(25 ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual __a = model(_a , _a ) if i + 1 == timesteps.shape[0]: __a = None else: __a = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a = scheduler.step( _a , _a , _a , prev_timestep=_a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass
11
0
import pickle import numpy as np from matplotlib import pyplot as plt class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a=0.2 , _a=0.2 ): __a = bp_numa __a = bp_numa __a = bp_numa __a = conva_get[:2] __a = conva_get[2] __a = size_pa __a = rate_w __a = rate_t __a = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] __a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) __a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) __a = -2 * np.random.rand(self.conva[1] ) + 1 __a = -2 * np.random.rand(self.num_bpa ) + 1 __a = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCAmelCase ( self , _a ): # save model dict with pickle __a = { '''num_bp1''': self.num_bpa, '''num_bp2''': self.num_bpa, '''num_bp3''': self.num_bpa, '''conv1''': self.conva, '''step_conv1''': self.step_conva, '''size_pooling1''': self.size_poolinga, '''rate_weight''': self.rate_weight, '''rate_thre''': self.rate_thre, '''w_conv1''': self.w_conva, '''wkj''': self.wkj, '''vji''': self.vji, '''thre_conv1''': self.thre_conva, '''thre_bp2''': self.thre_bpa, '''thre_bp3''': self.thre_bpa, } with open(_a , '''wb''' ) as f: pickle.dump(_a , _a ) print(f'''Model saved: {save_path}''' ) @classmethod def __UpperCAmelCase ( cls , _a ): # read saved model with open(_a , '''rb''' ) as f: __a = pickle.load(_a ) # noqa: S301 __a = model_dic.get('''conv1''' ) conv_get.append(model_dic.get('''step_conv1''' ) ) __a = model_dic.get('''size_pooling1''' ) __a = model_dic.get('''num_bp1''' ) __a = model_dic.get('''num_bp2''' ) __a = model_dic.get('''num_bp3''' ) __a = model_dic.get('''rate_weight''' ) __a = model_dic.get('''rate_thre''' ) # create model instance __a = CNN(_a , _a , _a , _a , _a , _a , _a ) # modify model parameter __a = model_dic.get('''w_conv1''' ) __a = model_dic.get('''wkj''' ) __a = model_dic.get('''vji''' ) __a = model_dic.get('''thre_conv1''' ) __a = model_dic.get('''thre_bp2''' ) __a = model_dic.get('''thre_bp3''' ) return conv_ins def __UpperCAmelCase ( self , _a ): return 1 / (1 + np.exp(-1 * x )) def __UpperCAmelCase ( self , _a ): return round(_a , 3 ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): # convolution process __a = convs[0] __a = convs[1] __a = np.shape(_a )[0] # get the data slice of original image data, data_focus __a = [] for i_focus in range(0 , size_data - size_conv + 1 , _a ): for j_focus in range(0 , size_data - size_conv + 1 , _a ): __a = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(_a ) # calculate the feature map of every single kernel, and saved as list of matrix __a = [] __a = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(_a ): __a = [] for i_focus in range(len(_a ) ): __a = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(_a ) ) __a = np.asmatrix(_a ).reshape( _a , _a ) data_featuremap.append(_a ) # expanding the data slice to One dimenssion __a = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(_a ) ) __a = np.asarray(_a ) return focus_list, data_featuremap def __UpperCAmelCase ( self , _a , _a , _a="average_pool" ): # pooling process __a = len(featuremaps[0] ) __a = int(size_map / size_pooling ) __a = [] for i_map in range(len(_a ) ): __a = featuremaps[i_map] __a = [] for i_focus in range(0 , _a , _a ): for j_focus in range(0 , _a , _a ): __a = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(_a ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(_a ) ) __a = np.asmatrix(_a ).reshape(_a , _a ) featuremap_pooled.append(_a ) return featuremap_pooled def __UpperCAmelCase ( self , _a ): # expanding three dimension data to one dimension list __a = [] for i in range(len(_a ) ): __a = np.shape(data[i] ) __a = data[i].reshape(1 , shapes[0] * shapes[1] ) __a = data_listed.getA().tolist()[0] data_expanded.extend(_a ) __a = np.asarray(_a ) return data_expanded def __UpperCAmelCase ( self , _a ): # expanding matrix to one dimension list __a = np.asarray(_a ) __a = np.shape(_a ) __a = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): __a = [] __a = 0 for i_map in range(_a ): __a = np.ones((size_map, size_map) ) for i in range(0 , _a , _a ): for j in range(0 , _a , _a ): __a = pd_pool[ i_pool ] __a = i_pool + 1 __a = np.multiply( _a , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(_a ) return pd_all def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=bool ): # model traning print('''----------------------Start Training-------------------------''' ) print((''' - - Shape: Train_Data ''', np.shape(_a )) ) print((''' - - Shape: Teach_Data ''', np.shape(_a )) ) __a = 0 __a = [] __a = 10_000 while rp < n_repeat and mse >= error_accuracy: __a = 0 print(f'''-------------Learning Time {rp}--------------''' ) for p in range(len(_a ) ): # print('------------Learning Image: %d--------------'%p) __a = np.asmatrix(datas_train[p] ) __a = np.asarray(datas_teach[p] ) __a , __a = self.convolute( _a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(_a , self.size_poolinga ) __a = np.shape(_a ) __a = self._expand(_a ) __a = data_bp_input __a = np.dot(_a , self.vji.T ) - self.thre_bpa __a = self.sig(_a ) __a = np.dot(_a , self.wkj.T ) - self.thre_bpa __a = self.sig(_a ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- __a = np.multiply( (data_teach - bp_outa) , np.multiply(_a , (1 - bp_outa) ) ) __a = np.multiply( np.dot(_a , self.wkj ) , np.multiply(_a , (1 - bp_outa) ) ) __a = np.dot(_a , self.vji ) __a = pd_i_all / (self.size_poolinga * self.size_poolinga) __a = pd_conva_pooled.T.getA().tolist() __a = self._calculate_gradient_from_pool( _a , _a , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): __a = self._expand_mat(pd_conva_all[k_conv] ) __a = self.rate_weight * np.dot(_a , _a ) __a = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) __a = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer __a = self.wkj + pd_k_all.T * bp_outa * self.rate_weight __a = self.vji + pd_j_all.T * bp_outa * self.rate_weight __a = self.thre_bpa - pd_k_all * self.rate_thre __a = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image __a = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) __a = rp + 1 __a = error_count / patterns all_mse.append(_a ) def draw_error(): __a = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(_a , '''+-''' ) plt.plot(_a , '''r--''' ) plt.xlabel('''Learning Times''' ) plt.ylabel('''All_mse''' ) plt.grid(_a , alpha=0.5 ) plt.show() print('''------------------Training Complished---------------------''' ) print((''' - - Training epoch: ''', rp, f''' - - Mse: {mse:.6f}''') ) if draw_e: draw_error() return mse def __UpperCAmelCase ( self , _a ): # model predict __a = [] print('''-------------------Start Testing-------------------------''' ) print((''' - - Shape: Test_Data ''', np.shape(_a )) ) for p in range(len(_a ) ): __a = np.asmatrix(datas_test[p] ) __a , __a = self.convolute( _a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(_a , self.size_poolinga ) __a = self._expand(_a ) __a = data_bp_input __a = bp_outa * self.vji.T - self.thre_bpa __a = self.sig(_a ) __a = bp_outa * self.wkj.T - self.thre_bpa __a = self.sig(_a ) produce_out.extend(bp_outa.getA().tolist() ) __a = [list(map(self.do_round , _a ) ) for each in produce_out] return np.asarray(_a ) def __UpperCAmelCase ( self , _a ): # return the data of image after convoluting process so we can check it out __a = np.asmatrix(_a ) __a , __a = self.convolute( _a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(_a , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
368
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
11
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a=2 , _a=3 , _a=64 , _a=None ): __a = np.random.default_rng(_a ) __a = length __a = rng.normal(size=(length,) ).astype(np.floataa ) __a = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ): return self.length def __getitem__( self , _a ): return {"x": self.x[i], "y": self.y[i]} class __lowerCAmelCase ( torch.nn.Module ): '''simple docstring''' def __init__( self , _a=0 , _a=0 , _a=False ): super().__init__() __a = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __a = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __a = True def __UpperCAmelCase ( self , _a=None ): if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) __a = False return x * self.a[0] + self.b[0] class __lowerCAmelCase ( torch.nn.Module ): '''simple docstring''' def __init__( self , _a=0 , _a=0 , _a=False ): super().__init__() __a = torch.nn.Parameter(torch.tensor(_a ).float() ) __a = torch.nn.Parameter(torch.tensor(_a ).float() ) __a = True def __UpperCAmelCase ( self , _a=None ): if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) __a = False return x * self.a + self.b def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : int = 16 ) -> List[str]: from datasets import load_dataset from transformers import AutoTokenizer __a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __a = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __a = load_dataset('''csv''' , data_files=lowerCAmelCase__ ) __a = datasets['''train'''].unique('''label''' ) __a = {v: i for i, v in enumerate(lowerCAmelCase__ )} def tokenize_function(lowerCAmelCase__ : int ): # max_length=None => use the model max length (it's actually the default) __a = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding='''max_length''' ) if "label" in examples: __a = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(lowerCAmelCase__ : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(lowerCAmelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __a = DataLoader(tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=2 ) __a = DataLoader(tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=1 ) return train_dataloader, eval_dataloader
369
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
0
lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
370
"""simple docstring""" from math import factorial, radians def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 18 , lowerCAmelCase__ : int = 10 ) -> float: __a = angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians __a = radians(lowerCAmelCase__ ) __a = angle_in_radians __a = 3 __a = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) __a = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__("doctest").testmod()
11
0
"""simple docstring""" from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = 'dandelin/vilt-b32-finetuned-vqa' __UpperCAmelCase : int = ( 'This is a tool that answers a question about an image. It takes an input named `image` which should be the ' 'image containing the information, as well as a `question` which should be the question in English. It ' 'returns a text that is the answer to the question.' ) __UpperCAmelCase : Any = 'image_qa' __UpperCAmelCase : Union[str, Any] = AutoProcessor __UpperCAmelCase : str = AutoModelForVisualQuestionAnswering __UpperCAmelCase : List[str] = ['image', 'text'] __UpperCAmelCase : List[str] = ['text'] def __init__( self , *_a , **_a ): requires_backends(self , ['''vision'''] ) super().__init__(*_a , **_a ) def __UpperCAmelCase ( self , _a , _a ): return self.pre_processor(_a , _a , return_tensors='''pt''' ) def __UpperCAmelCase ( self , _a ): with torch.no_grad(): return self.model(**_a ).logits def __UpperCAmelCase ( self , _a ): __a = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
371
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowercase ( lowerCAmelCase__ : dict ) -> tuple: return (data["data"], data["target"]) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ) -> np.ndarray: __a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowerCAmelCase__ , lowerCAmelCase__ ) # Predict target for test data __a = xgb.predict(lowerCAmelCase__ ) __a = predictions.reshape(len(lowerCAmelCase__ ) , 1 ) return predictions def lowercase ( ) -> None: __a = fetch_california_housing() __a , __a = data_handling(lowerCAmelCase__ ) __a , __a , __a , __a = train_test_split( lowerCAmelCase__ , lowerCAmelCase__ , test_size=0.25 , random_state=1 ) __a = xgboost(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
11
0
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] ) -> List[str]: __a = UniSpeechSatForSequenceClassification.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ ) __a = downstream_dict['''projector.weight'''] __a = downstream_dict['''projector.bias'''] __a = downstream_dict['''model.post_net.linear.weight'''] __a = downstream_dict['''model.post_net.linear.bias'''] return model def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any ) -> Tuple: __a = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ ) __a = downstream_dict['''model.linear.weight'''] __a = downstream_dict['''model.linear.bias'''] return model def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : Any ) -> Tuple: __a = UniSpeechSatForXVector.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ ) __a = downstream_dict['''connector.weight'''] __a = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __a = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] __a = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] __a = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] __a = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] __a = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] __a = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] __a = downstream_dict['''objective.W'''] return model @torch.no_grad() def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str , lowerCAmelCase__ : Union[str, Any] ) -> Tuple: __a = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) __a = checkpoint['''Downstream'''] __a = UniSpeechSatConfig.from_pretrained(lowerCAmelCase__ ) __a = WavaVecaFeatureExtractor.from_pretrained( lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , do_normalize=lowerCAmelCase__ ) __a = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): __a = convert_classification(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) elif arch.endswith('''ForAudioFrameClassification''' ): __a = convert_diarization(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) elif arch.endswith('''ForXVector''' ): __a = convert_xvector(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: __a = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(lowerCAmelCase__ ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowercase_ = 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.") lowercase_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = 10 def __UpperCAmelCase ( self ): __a = [1, 2, 3, 4] __a = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(_a , self.block_size , 0 ) , _a ) def __UpperCAmelCase ( self ): __a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] __a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_a , self.block_size , 0 ) , _a ) def __UpperCAmelCase ( self ): __a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] __a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_a , self.block_size , 0 ) , _a ) def __UpperCAmelCase ( self ): __a = '''It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.''' __a , __a = process_story(_a ) self.assertEqual(_a , [] ) def __UpperCAmelCase ( self ): __a = '''''' __a , __a = process_story(_a ) self.assertEqual(_a , [] ) self.assertEqual(_a , [] ) def __UpperCAmelCase ( self ): __a = ( '''It was the year of Our Lord one thousand seven hundred and ''' '''seventy-five\n\nSpiritual revelations were conceded to England ''' '''at that favoured period, as at this.\n@highlight\n\nIt was the best of times''' ) __a , __a = process_story(_a ) __a = [ '''It was the year of Our Lord one thousand seven hundred and seventy-five.''', '''Spiritual revelations were conceded to England at that favoured period, as at this.''', ] self.assertEqual(_a , _a ) __a = ['''It was the best of times.'''] self.assertEqual(_a , _a ) def __UpperCAmelCase ( self ): __a = torch.tensor([1, 2, 3, 4] ) __a = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(_a , 0 ).numpy() , expected.numpy() ) def __UpperCAmelCase ( self ): __a = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) __a = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_a , 23 ).numpy() , expected.numpy() ) def __UpperCAmelCase ( self ): __a = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) __a = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_a , 1 ).numpy() , expected.numpy() ) def __UpperCAmelCase ( self ): __a = 101 __a = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) __a = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) __a = compute_token_type_ids(_a , _a ) np.testing.assert_array_equal(_a , _a )
351
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'funnel' __UpperCAmelCase : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', } def __init__( self , _a=30_522 , _a=[4, 4, 4] , _a=None , _a=2 , _a=768 , _a=12 , _a=64 , _a=3_072 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=None , _a=1E-9 , _a="mean" , _a="relative_shift" , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = block_sizes __a = [1] * len(_a ) if block_repeats is None else block_repeats assert len(_a ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __a = num_decoder_layers __a = d_model __a = n_head __a = d_head __a = d_inner __a = hidden_act __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = initializer_range __a = initializer_std __a = layer_norm_eps assert pooling_type in [ "mean", "max", ], f'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' __a = pooling_type assert attention_type in [ "relative_shift", "factorized", ], f'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' __a = attention_type __a = separate_cls __a = truncate_seq __a = pool_q_only super().__init__(**_a ) @property def __UpperCAmelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.''' ) @property def __UpperCAmelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self , _a ): raise NotImplementedError('''This model does not support the setting of `num_blocks`. Please set `block_sizes`.''' )
11
0
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list ) -> float: if not nums: raise ValueError('''List is empty''' ) return sum(lowerCAmelCase__ ) / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
352
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = 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, ) , ) __a = 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 __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 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 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> str: __a = 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 ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_a ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _a ) __a = image_processor.post_process_semantic_segmentation(outputs=_a ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _a )
11
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset lowercase_ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class __lowerCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _a ): super().__init__() __a = torchvision.models.resnetaaa(pretrained=_a ) __a = list(model.children() )[:-2] __a = nn.Sequential(*_a ) __a = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def __UpperCAmelCase ( self , _a ): # Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048 __a = self.pool(self.model(_a ) ) __a = torch.flatten(_a , start_dim=2 ) __a = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a ): __a = [json.loads(_a ) for l in open(_a )] __a = os.path.dirname(_a ) __a = tokenizer __a = labels __a = len(_a ) __a = max_seq_length __a = transforms def __len__( self ): return len(self.data ) def __getitem__( self , _a ): __a = torch.LongTensor(self.tokenizer.encode(self.data[index]['''text'''] , add_special_tokens=_a ) ) __a , __a , __a = sentence[0], sentence[1:-1], sentence[-1] __a = sentence[: self.max_seq_length] __a = torch.zeros(self.n_classes ) __a = 1 __a = Image.open(os.path.join(self.data_dir , self.data[index]['''img'''] ) ).convert('''RGB''' ) __a = self.transforms(_a ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def __UpperCAmelCase ( self ): __a = Counter() for row in self.data: label_freqs.update(row['''label'''] ) return label_freqs def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a = [len(row['''sentence'''] ) for row in batch] __a , __a = len(lowerCAmelCase__ ), max(lowerCAmelCase__ ) __a = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ , dtype=torch.long ) __a = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ): __a = input_row['''sentence'''] __a = 1 __a = torch.stack([row['''image'''] for row in batch] ) __a = torch.stack([row['''label'''] for row in batch] ) __a = torch.stack([row['''image_start_token'''] for row in batch] ) __a = torch.stack([row['''image_end_token'''] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def lowercase ( ) -> int: return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def lowercase ( ) -> str: return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_77_70_44, 0.44_53_14_29, 0.40_66_10_17] , std=[0.12_22_19_94, 0.12_14_58_35, 0.14_38_04_69] , ), ] )
353
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
11
0
"""simple docstring""" import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a = True , _a = False ): __a = scheduler __a = optimizers if isinstance(_a , (list, tuple) ) else [optimizers] __a = split_batches __a = step_with_optimizer __a = GradientState() def __UpperCAmelCase ( self , *_a , **_a ): if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*_a , **_a ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*_a , **_a ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step __a = AcceleratorState().num_processes for _ in range(_a ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*_a , **_a ) else: self.scheduler.step(*_a , **_a ) def __UpperCAmelCase ( self ): return self.scheduler.get_last_lr() def __UpperCAmelCase ( self ): return self.scheduler.state_dict() def __UpperCAmelCase ( self , _a ): self.scheduler.load_state_dict(_a ) def __UpperCAmelCase ( self ): return self.scheduler.get_lr() def __UpperCAmelCase ( self , *_a , **_a ): return self.scheduler.print_lr(*_a , **_a )
354
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_a ): super().__init__(**_a ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __UpperCAmelCase ( self , _a , _a=None , _a="This is a sound of {}." ): if isinstance(_a , _a ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(_a ).content else: with open(_a , '''rb''' ) as f: __a = f.read() if isinstance(_a , _a ): __a = ffmpeg_read(_a , self.feature_extractor.sampling_rate ) if not isinstance(_a , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) __a = candidate_labels __a = [hypothesis_template.format(_a ) for x in candidate_labels] __a = self.tokenizer(_a , return_tensors=self.framework , padding=_a ) __a = [text_inputs] return inputs def __UpperCAmelCase ( self , _a ): __a = model_inputs.pop('''candidate_labels''' ) __a = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _a ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**_a , **_a ) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.pop('''candidate_labels''' ) __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_a , _a ) , key=lambda _a : -x[0] ) ] return result
11
0
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase ( lowerCAmelCase__ : Dict ) -> Optional[int]: __a , __a = image.size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 __a = image[None].transpose(0 , 3 , 1 , 2 ) __a = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = None , _a = 1 , _a = 100 , _a = 0.0 , _a = None , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}''' ) if isinstance(_a , PIL.Image.Image ): __a = preprocess(_a ) __a , __a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __a = (batch_size, self.unet.config.in_channels // 2, height, width) __a = next(self.unet.parameters() ).dtype __a = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) __a = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) __a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. __a = torch.cat([latents, image] , dim=1 ) __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE __a = self.vqvae.decode(_a ).sample __a = torch.clamp(_a , -1.0 , 1.0 ) __a = image / 2 + 0.5 __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
355
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __a = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sgugger/tiny-distilbert-classification''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , only_pretrain_model=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , torchscript=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , fpaa=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) # set architectures equal to `None` __a = None __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tinier_bart''' __a = AutoConfig.from_pretrained(_a ) __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_a , ) __a = PyTorchBenchmark(_a , configs=[config] ) __a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , save_to_csv=_a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_a , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(_a , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(_a , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(_a , '''train_time.csv''' ) , env_info_csv_file=os.path.join(_a , '''env.csv''' ) , multi_process=_a , ) __a = PyTorchBenchmark(_a ) benchmark.run() self.assertTrue(Path(os.path.join(_a , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_a , '''env.csv''' ) ).exists() ) def __UpperCAmelCase ( self ): __a = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_a , '''sequential''' ) ) self.assertTrue(hasattr(_a , '''cumulative''' ) ) self.assertTrue(hasattr(_a , '''current''' ) ) self.assertTrue(hasattr(_a , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_a , inference=_a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_a , '''log.txt''' ) , log_print=_a , trace_memory_line_by_line=_a , multi_process=_a , ) __a = PyTorchBenchmark(_a ) __a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_a , '''log.txt''' ) ).exists() )
11
0
"""simple docstring""" import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict ) -> Dict: __a = set() __a = [] def parse_line(lowerCAmelCase__ : Any ): for line in fp: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(lowerCAmelCase__ ) > 0: __a = '''\n'''.join(lowerCAmelCase__ ) # Only keep the warnings specified in `targets` if any(f''': {x}: ''' in warning for x in targets ): selected_warnings.add(lowerCAmelCase__ ) buffer.clear() continue else: __a = line.strip() buffer.append(lowerCAmelCase__ ) if from_gh: for filename in os.listdir(lowerCAmelCase__ ): __a = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) if not os.path.isdir(lowerCAmelCase__ ): # read the file if filename != "warnings.txt": continue with open(lowerCAmelCase__ ) as fp: parse_line(lowerCAmelCase__ ) else: try: with zipfile.ZipFile(lowerCAmelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase__ ): # read the file if filename != "warnings.txt": continue with z.open(lowerCAmelCase__ ) as fp: parse_line(lowerCAmelCase__ ) except Exception: logger.warning( f'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: __a = set() __a = [os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) for p in os.listdir(lowerCAmelCase__ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowerCAmelCase__ , lowerCAmelCase__ ) ) return selected_warnings if __name__ == "__main__": def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> int: return values.split(''',''' ) lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") # optional parameters parser.add_argument( "--targets", default="DeprecationWarning,UserWarning,FutureWarning", type=list_str, help="Comma-separated list of target warning(s) which we want to extract.", ) parser.add_argument( "--from_gh", action="store_true", help="If running from a GitHub action workflow and collecting warnings from its artifacts.", ) lowercase_ = parser.parse_args() lowercase_ = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links lowercase_ = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("=" * 8_0) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts lowercase_ = extract_warnings(args.output_dir, args.targets) lowercase_ = sorted(selected_warnings) with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
356
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
0
"""simple docstring""" lowercase_ = { "meter": "m", "kilometer": "km", "megametre": "Mm", "gigametre": "Gm", "terametre": "Tm", "petametre": "Pm", "exametre": "Em", "zettametre": "Zm", "yottametre": "Ym", } # Exponent of the factor(meter) lowercase_ = { "m": 0, "km": 3, "Mm": 6, "Gm": 9, "Tm": 1_2, "Pm": 1_5, "Em": 1_8, "Zm": 2_1, "Ym": 2_4, } def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = from_type.lower().strip('''s''' ) __a = to_type.lower().strip('''s''' ) __a = UNIT_SYMBOL.get(lowerCAmelCase__ , lowerCAmelCase__ ) __a = UNIT_SYMBOL.get(lowerCAmelCase__ , lowerCAmelCase__ ) if from_sanitized not in METRIC_CONVERSION: __a = ( f'''Invalid \'from_type\' value: {from_type!r}.\n''' f'''Conversion abbreviations are: {', '.join(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) if to_sanitized not in METRIC_CONVERSION: __a = ( f'''Invalid \'to_type\' value: {to_type!r}.\n''' f'''Conversion abbreviations are: {', '.join(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) __a = METRIC_CONVERSION[from_sanitized] __a = METRIC_CONVERSION[to_sanitized] __a = 1 if from_exponent > to_exponent: __a = from_exponent - to_exponent else: __a = -(to_exponent - from_exponent) return value * pow(10 , lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
357
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): self.assertEqual(len(_a ) , len(_a ) ) for a, b in zip(_a , _a ): self.assertAlmostEqual(_a , _a , delta=_a ) def __UpperCAmelCase ( self ): __a = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_a ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def __UpperCAmelCase ( self ): __a = None ops.enable_eager_execution_internal() __a = tf.config.list_physical_devices('''CPU''' ) if len(_a ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a = tf.config.list_logical_devices(device_type='''CPU''' ) __a = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a = GradientAccumulator() __a = tf.Variable([4.0, 3.0] ) __a , __a = create_optimizer(5E-5 , 10 , 5 ) __a = tf.Variable([0.0, 0.0] , trainable=_a ) def accumulate_on_replica(_a ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_a , _a ): with strategy.scope(): __a = strategy.experimental_local_results(_a ) local_variables[0].assign(_a ) local_variables[1].assign(_a ) strategy.run(_a , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_a ) def _check_local_values(_a , _a ): __a = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _a , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _a , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
11
0