code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCAmelCase__ : List[str] = logging.get_logger(__name__) lowerCAmelCase__ : List[Any] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn.grep_linear': 'encoder.layers.*.attention.gru_rel_pos_linear', 'self_attn.relative_attention_bias': 'encoder.layers.*.attention.rel_attn_embed', 'self_attn.grep_a': 'encoder.layers.*.attention.gru_rel_pos_const', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'ctc_proj', 'mask_emb': 'masked_spec_embed', } lowerCAmelCase__ : Union[str, Any] = [ 'ctc_proj', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): for attribute in key.split('.' ): UpperCAmelCase__ = getattr(lowerCamelCase , lowerCamelCase ) if weight_type is not None: UpperCAmelCase__ = getattr(lowerCamelCase , lowerCamelCase ).shape else: UpperCAmelCase__ = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCAmelCase__ = value elif weight_type == "weight_g": UpperCAmelCase__ = value elif weight_type == "weight_v": UpperCAmelCase__ = value elif weight_type == "bias": UpperCAmelCase__ = value else: UpperCAmelCase__ = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def a_ ( lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = [] UpperCAmelCase__ = fairseq_model.state_dict() UpperCAmelCase__ = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCAmelCase__ = False if "conv_layers" in name: load_conv_layer( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , hf_model.config.feat_extract_norm == 'group' , ) UpperCAmelCase__ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCAmelCase__ = True if "*" in mapped_key: UpperCAmelCase__ = name.split(lowerCamelCase )[0].split('.' )[-2] UpperCAmelCase__ = mapped_key.replace('*' , lowerCamelCase ) if "weight_g" in name: UpperCAmelCase__ = 'weight_g' elif "weight_v" in name: UpperCAmelCase__ = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: UpperCAmelCase__ = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCAmelCase__ = 'weight' else: UpperCAmelCase__ = None set_recursively(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) continue if not is_used: unused_weights.append(lowerCamelCase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = full_name.split('conv_layers.' )[-1] UpperCAmelCase__ = name.split('.' ) UpperCAmelCase__ = int(items[0] ) UpperCAmelCase__ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCAmelCase__ = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCAmelCase__ = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) UpperCAmelCase__ = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCAmelCase__ = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCamelCase ) @torch.no_grad() def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=None ): # load the pre-trained checkpoints UpperCAmelCase__ = torch.load(lowerCamelCase ) UpperCAmelCase__ = WavLMConfigOrig(checkpoint['cfg'] ) UpperCAmelCase__ = WavLMOrig(lowerCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: UpperCAmelCase__ = WavLMConfig.from_pretrained(lowerCamelCase ) else: UpperCAmelCase__ = WavLMConfig() UpperCAmelCase__ = WavLMModel(lowerCamelCase ) recursively_load_weights(lowerCamelCase , lowerCamelCase ) hf_wavlm.save_pretrained(lowerCamelCase ) if __name__ == "__main__": lowerCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') lowerCAmelCase__ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
98
'''simple docstring''' import warnings from ..trainer import Trainer from ..utils import logging __a = logging.get_logger(__name__) class A__ ( UpperCamelCase ): """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase__ : List[str]=None , **lowerCAmelCase__ : List[str] ) -> Union[str, Any]: """simple docstring""" warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , lowerCAmelCase__ , ) super().__init__(args=lowerCAmelCase__ , **lowerCAmelCase__ )
145
0
'''simple docstring''' from statistics import mean import numpy as np def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Tuple = 0 # Number of processes finished __UpperCAmelCase : Optional[int] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. __UpperCAmelCase : Tuple = [0] * no_of_process # List to include calculation results __UpperCAmelCase : int = [0] * no_of_process # Sort by arrival time. __UpperCAmelCase : Dict = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] __UpperCAmelCase : Union[str, Any] = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: __UpperCAmelCase : Dict = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: __UpperCAmelCase : Any = arrival_time[i] __UpperCAmelCase : Any = 0 # Index showing the location of the process being performed __UpperCAmelCase : Any = 0 # Saves the current response ratio. __UpperCAmelCase : List[str] = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: __UpperCAmelCase : Dict = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: __UpperCAmelCase : Tuple = temp __UpperCAmelCase : List[str] = i # Calculate the turn around time __UpperCAmelCase : Tuple = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. __UpperCAmelCase : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[int] = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): __UpperCAmelCase : List[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _UpperCamelCase = 5 _UpperCamelCase = ['''A''', '''B''', '''C''', '''D''', '''E'''] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _UpperCamelCase = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
16
'''simple docstring''' from statistics import mean import numpy as np def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Tuple = 0 # Number of processes finished __UpperCAmelCase : Optional[int] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. __UpperCAmelCase : Tuple = [0] * no_of_process # List to include calculation results __UpperCAmelCase : int = [0] * no_of_process # Sort by arrival time. __UpperCAmelCase : Dict = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] __UpperCAmelCase : Union[str, Any] = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: __UpperCAmelCase : Dict = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: __UpperCAmelCase : Any = arrival_time[i] __UpperCAmelCase : Any = 0 # Index showing the location of the process being performed __UpperCAmelCase : Any = 0 # Saves the current response ratio. __UpperCAmelCase : List[str] = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: __UpperCAmelCase : Dict = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: __UpperCAmelCase : Tuple = temp __UpperCAmelCase : List[str] = i # Calculate the turn around time __UpperCAmelCase : Tuple = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. __UpperCAmelCase : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[int] = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): __UpperCAmelCase : List[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _UpperCamelCase = 5 _UpperCamelCase = ['''A''', '''B''', '''C''', '''D''', '''E'''] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _UpperCamelCase = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
16
1
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : """simple docstring""" def __init__( self , __A , __A=13 , __A=7 , __A=True , __A=True , __A=True , __A=True , __A=99 , __A=24 , __A=2 , __A=6 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=16 , __A=2 , __A=0.02 , __A=3 , __A=None , __A=1000 , ) -> str: 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 =scope a =range_bbox def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a =ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # 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 =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 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 =self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self ) -> Tuple: return LiltConfig( 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 , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> Any: a =LiltModel(config=__A ) model.to(__A ) model.eval() a =model(__A , bbox=__A , attention_mask=__A , token_type_ids=__A ) a =model(__A , bbox=__A , token_type_ids=__A ) a =model(__A , bbox=__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 SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> List[str]: a =self.num_labels a =LiltForTokenClassification(config=__A ) model.to(__A ) model.eval() a =model( __A , bbox=__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 SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> Any: a =LiltForQuestionAnswering(config=__A ) model.to(__A ) model.eval() a =model( __A , bbox=__A , attention_mask=__A , token_type_ids=__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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.prepare_config_and_inputs() ( ( 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_torch class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowerCAmelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A ) -> Any: return True def SCREAMING_SNAKE_CASE ( self ) -> Any: a =LiltModelTester(self ) a =ConfigTester(self , config_class=__A , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a =type self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> str: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =LiltModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_torch @slow class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__A ) a =torch.tensor([[1, 2]] , device=__A ) a =torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__A ) # forward pass with torch.no_grad(): a =model(input_ids=__A , bbox=__A ) a =torch.Size([1, 2, 768] ) a =torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=__A , ) self.assertTrue(outputs.last_hidden_state.shape , __A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __A , atol=1E-3 ) )
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder UpperCamelCase__ = datasets.utils.logging.get_logger(__name__) class a__ ( folder_based_builder.FolderBasedBuilderConfig ): _a : bool = None _a : bool = None class a__ ( folder_based_builder.FolderBasedBuilder ): _a : List[str] = datasets.Audio() _a : Union[str, Any] = '''audio''' _a : Optional[Any] = AudioFolderConfig _a : List[str] # definition at the bottom of the script _a : List[Any] = AudioClassification(audio_column="""audio""" , label_column="""label""" ) UpperCamelCase__ = [ """.aiff""", """.au""", """.avr""", """.caf""", """.flac""", """.htk""", """.svx""", """.mat4""", """.mat5""", """.mpc2k""", """.ogg""", """.paf""", """.pvf""", """.raw""", """.rf64""", """.sd2""", """.sds""", """.ircam""", """.voc""", """.w64""", """.wav""", """.nist""", """.wavex""", """.wve""", """.xi""", """.mp3""", """.opus""", ] UpperCamelCase__ = AUDIO_EXTENSIONS
363
from sklearn.metrics import mean_squared_error import datasets UpperCamelCase__ = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ UpperCamelCase__ = """\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. """ UpperCamelCase__ = """ Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. \"raw_values\" : Returns a full set of errors in case of multioutput input. \"uniform_average\" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric(\"mse\") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {'mse': 0.6123724356957945} If you're using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {'mse': array([0.41666667, 1. ])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html" ] , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("float" ) ), "references": datasets.Sequence(datasets.Value("float" ) ), } else: return { "predictions": datasets.Value("float" ), "references": datasets.Value("float" ), } def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A="uniform_average" , _A=True ): """simple docstring""" __lowerCAmelCase = mean_squared_error( _A , _A , sample_weight=_A , multioutput=_A , squared=_A ) return {"mse": mse}
102
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : int = { '''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: a__ : List[str] = [ '''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 a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path __lowerCAmelCase : Any = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def a__ ( A_=True ): '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=_A ) ) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = None a__ = None def _lowercase ( self : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] ) -> Tuple: """simple docstring""" with TemporaryDirectory() as tmp_dir: __magic_name__ = dataset_module_factory(UpperCamelCase__ , cache_dir=UpperCamelCase__ ) __magic_name__ = import_main_class(dataset_module.module_path , dataset=UpperCamelCase__ ) __magic_name__ = builder_cls( cache_dir=UpperCamelCase__ , config_name=UpperCamelCase__ , hash=dataset_module.hash , ) __magic_name__ = """/""".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=UpperCamelCase__ ).replace(os.sep , """/""" ), config.DATASET_INFO_FILENAME, ] ) __magic_name__ = cached_path(UpperCamelCase__ , cache_dir=UpperCamelCase__ ) self.assertTrue(os.path.exists(UpperCamelCase__ ) ) @pytest.mark.integration def a__ ( A_ ): '''simple docstring''' __magic_name__ = tmp_path_factory.mktemp("""test_hf_gcp""" ) / """test_wikipedia_simple""" __magic_name__ = dataset_module_factory("""wikipedia""", cache_dir=A_ ) __magic_name__ = import_main_class(dataset_module.module_path ) __magic_name__ = builder_cls( cache_dir=A_, config_name="""20220301.frr""", hash=dataset_module.hash, ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam __magic_name__ = None builder_instance.download_and_prepare() __magic_name__ = builder_instance.as_dataset() assert ds @pytest.mark.integration def a__ ( A_ ): '''simple docstring''' __magic_name__ = dataset_module_factory("""wikipedia""", cache_dir=A_ ) __magic_name__ = import_main_class(dataset_module.module_path, dataset=A_ ) __magic_name__ = builder_cls( cache_dir=A_, config_name="""20220301.frr""", hash=dataset_module.hash, ) __magic_name__ = builder_instance.as_streaming_dataset() assert ds assert isinstance(A_, A_ ) assert "train" in ds assert isinstance(ds["""train"""], A_ ) assert next(iter(ds["""train"""] ) )
88
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class a ( unittest.TestCase ): """simple docstring""" def __init__( self: str , UpperCamelCase: List[str] , UpperCamelCase: Optional[int]=13 , UpperCamelCase: Union[str, Any]=30 , UpperCamelCase: Optional[Any]=2 , UpperCamelCase: Any=3 , UpperCamelCase: str=True , UpperCamelCase: Any=True , UpperCamelCase: List[Any]=32 , UpperCamelCase: Optional[Any]=5 , UpperCamelCase: Optional[int]=4 , UpperCamelCase: int=37 , UpperCamelCase: str="gelu" , UpperCamelCase: str=0.1 , UpperCamelCase: Tuple=0.1 , UpperCamelCase: List[str]=10 , UpperCamelCase: Dict=0.02 , ): """simple docstring""" A__ = parent A__ = batch_size A__ = image_size A__ = patch_size A__ = num_channels A__ = is_training A__ = use_labels 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__ = type_sequence_label_size A__ = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A__ = (image_size // patch_size) ** 2 A__ = num_patches + 1 def UpperCamelCase ( self: Optional[int] ): """simple docstring""" A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase , initializer_range=self.initializer_range , ) return config, pixel_values def UpperCamelCase ( self: Tuple , UpperCamelCase: Union[str, Any] , UpperCamelCase: Optional[Any] ): """simple docstring""" A__ = FlaxViTModel(config=UpperCamelCase ) A__ = model(UpperCamelCase ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) A__ = (self.image_size, self.image_size) A__ = (self.patch_size, self.patch_size) A__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def UpperCamelCase ( self: Optional[int] , UpperCamelCase: Any , UpperCamelCase: Any ): """simple docstring""" A__ = self.type_sequence_label_size A__ = FlaxViTForImageClassification(config=UpperCamelCase ) A__ = model(UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ = 1 A__ = FlaxViTForImageClassification(UpperCamelCase ) A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(UpperCamelCase ) def UpperCamelCase ( self: str ): """simple docstring""" A__ = self.prepare_config_and_inputs() ( A__ ) = config_and_inputs A__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class a ( _a, unittest.TestCase ): """simple docstring""" UpperCAmelCase = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def UpperCamelCase ( self: Union[str, Any] ): """simple docstring""" A__ = FlaxViTModelTester(self ) A__ = ConfigTester(self , config_class=UpperCamelCase , has_text_modality=UpperCamelCase , hidden_size=37 ) def UpperCamelCase ( self: Any ): """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self: Optional[Any] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase ) def UpperCamelCase ( self: List[Any] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(UpperCamelCase ) A__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , UpperCamelCase ) def UpperCamelCase ( self: Tuple ): """simple docstring""" 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(UpperCamelCase , UpperCamelCase ) A__ = model_class(UpperCamelCase ) @jax.jit def model_jitted(UpperCamelCase: int , **UpperCamelCase: List[str] ): return model(pixel_values=UpperCamelCase , **UpperCamelCase ) with self.subTest("""JIT Enabled""" ): A__ = model_jitted(**UpperCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): A__ = model_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase , UpperCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase ( self: Any ): """simple docstring""" for model_class_name in self.all_model_classes: A__ = model_class_name.from_pretrained("""google/vit-base-patch16-224""" ) A__ = model(np.ones((1, 3, 2_24, 2_24) ) ) self.assertIsNotNone(UpperCamelCase )
367
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_tests_dir('fixtures/test_sentencepiece_bpe.model') class a ( _lowerCamelCase, unittest.TestCase ): """simple docstring""" UpperCAmelCase = BartphoTokenizer UpperCAmelCase = False UpperCAmelCase = True def UpperCamelCase ( self: Optional[Any] ): """simple docstring""" super().setUp() A__ = ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] A__ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) A__ = {"""unk_token""": """<unk>"""} A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""monolingual_vocab_file"""] ) with open(self.monolingual_vocab_file , """w""" , encoding="""utf-8""" ) as fp: for token in vocab_tokens: fp.write(f"""{token} {vocab_tokens[token]}\n""" ) A__ = BartphoTokenizer(UpperCamelCase , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self: Dict , **UpperCamelCase: Tuple ): """simple docstring""" kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase ( self: Union[str, Any] , UpperCamelCase: Tuple ): """simple docstring""" A__ = """This is a là test""" A__ = """This is a<unk><unk> test""" return input_text, output_text def UpperCamelCase ( self: Union[str, Any] ): """simple docstring""" A__ = BartphoTokenizer(UpperCamelCase , self.monolingual_vocab_file , **self.special_tokens_map ) A__ = """This is a là test""" A__ = """▁This ▁is ▁a ▁l à ▁t est""".split() A__ = tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) A__ = tokens + [tokenizer.unk_token] A__ = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , UpperCamelCase )
69
0
'''simple docstring''' a__ : List[str] ='ABCDEFGHIJKLMNOPQRSTUVWXYZ' def lowercase__ ( ) -> Dict: """simple docstring""" __UpperCamelCase = input('Enter message: ' ) __UpperCamelCase = input('Enter key [alphanumeric]: ' ) __UpperCamelCase = input('Encrypt/Decrypt [e/d]: ' ) if mode.lower().startswith('e' ): __UpperCamelCase = '''encrypt''' __UpperCamelCase = encrypt_message(_UpperCAmelCase , _UpperCAmelCase ) elif mode.lower().startswith('d' ): __UpperCamelCase = '''decrypt''' __UpperCamelCase = decrypt_message(_UpperCAmelCase , _UpperCAmelCase ) print(F'''\n{mode.title()}ed message:''' ) print(_UpperCAmelCase ) def lowercase__ ( __lowercase : str , __lowercase : Tuple ) -> str: """simple docstring""" return translate_message(_UpperCAmelCase , _UpperCAmelCase , 'encrypt' ) def lowercase__ ( __lowercase : int , __lowercase : str ) -> Tuple: """simple docstring""" return translate_message(_UpperCAmelCase , _UpperCAmelCase , 'decrypt' ) def lowercase__ ( __lowercase : Optional[int] , __lowercase : Tuple , __lowercase : Any ) -> str: """simple docstring""" __UpperCamelCase = [] __UpperCamelCase = 0 __UpperCamelCase = key.upper() for symbol in message: __UpperCamelCase = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_UpperCAmelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_UpperCAmelCase ): __UpperCamelCase = 0 else: translated.append(_UpperCAmelCase ) return "".join(_UpperCAmelCase ) if __name__ == "__main__": main()
53
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowercase ( __UpperCAmelCase , __UpperCAmelCase): __lowerCAmelCase : List[Any] = """convnextv2""" def __init__( self : int , _lowerCamelCase : str=3 , _lowerCamelCase : str=4 , _lowerCamelCase : List[Any]=4 , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : List[Any]=None , _lowerCamelCase : Optional[int]="gelu" , _lowerCamelCase : Union[str, Any]=0.02 , _lowerCamelCase : List[str]=1E-12 , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : Optional[int]=2_24 , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : Optional[Any]=None , **_lowerCamelCase : Optional[Any] , ): """simple docstring""" super().__init__(**_lowerCamelCase ) A_ : str = num_channels A_ : int = patch_size A_ : Union[str, Any] = num_stages A_ : Any = [96, 1_92, 3_84, 7_68] if hidden_sizes is None else hidden_sizes A_ : Any = [3, 3, 9, 3] if depths is None else depths A_ : Optional[int] = hidden_act A_ : Tuple = initializer_range A_ : int = layer_norm_eps A_ : List[Any] = drop_path_rate A_ : Union[str, Any] = image_size A_ : Any = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] A_ , A_ : Tuple = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names )
167
0
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def snake_case_ (__A : str , __A : str , **__A : Union[str, Any] ) -> List[str]: __lowerCAmelCase : List[str] = AutoConfig.from_pretrained(__A , **__A ) __lowerCAmelCase : List[str] = AutoModelForSeqaSeqLM.from_config(__A ) model.save_pretrained(__A ) AutoTokenizer.from_pretrained(__A ).save_pretrained(__A ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
139
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( a_ , a_ , unittest.TestCase ): """simple docstring""" lowerCamelCase : Tuple =AutoencoderKL lowerCamelCase : Tuple ="sample" lowerCamelCase : Dict =1e-2 @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: """simple docstring""" __lowerCAmelCase : str = 4 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Optional[Any] = (32, 32) __lowerCAmelCase : Union[str, Any] = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCAmelCase ) return {"sample": image} @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: """simple docstring""" return (3, 32, 32) @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: """simple docstring""" return (3, 32, 32) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: """simple docstring""" __lowerCAmelCase : List[Any] = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __lowerCAmelCase : Optional[int] = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE ( self : int ) -> str: """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" pass @unittest.skipIf(torch_device == """mps""" , """Gradient checkpointing skipped on MPS""" ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: """simple docstring""" __lowerCAmelCase ,__lowerCAmelCase : str = self.prepare_init_args_and_inputs_for_common() __lowerCAmelCase : Dict = self.model_class(**lowerCAmelCase ) model.to(lowerCAmelCase ) assert not model.is_gradient_checkpointing and model.training __lowerCAmelCase : str = model(**lowerCAmelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __lowerCAmelCase : Any = torch.randn_like(lowerCAmelCase ) __lowerCAmelCase : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __lowerCAmelCase : List[str] = self.model_class(**lowerCAmelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCAmelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __lowerCAmelCase : Any = model_a(**lowerCAmelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __lowerCAmelCase : Dict = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) __lowerCAmelCase : int = dict(model.named_parameters() ) __lowerCAmelCase : Union[str, Any] = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: """simple docstring""" __lowerCAmelCase ,__lowerCAmelCase : List[Any] = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" , output_loading_info=lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(lowerCAmelCase ) __lowerCAmelCase : int = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: """simple docstring""" __lowerCAmelCase : Dict = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" ) __lowerCAmelCase : Optional[Any] = model.to(lowerCAmelCase ) model.eval() if torch_device == "mps": __lowerCAmelCase : List[Any] = torch.manual_seed(0 ) else: __lowerCAmelCase : Any = torch.Generator(device=lowerCAmelCase ).manual_seed(0 ) __lowerCAmelCase : Optional[int] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __lowerCAmelCase : Optional[int] = image.to(lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = model(lowerCAmelCase , sample_posterior=lowerCAmelCase , generator=lowerCAmelCase ).sample __lowerCAmelCase : Dict = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __lowerCAmelCase : List[str] = torch.tensor( [ -4.0078e-01, -3.8323e-04, -1.2681e-01, -1.1462e-01, 2.0095e-01, 1.0893e-01, -8.8247e-02, -3.0361e-01, -9.8644e-03, ] ) elif torch_device == "cpu": __lowerCAmelCase : Union[str, Any] = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: __lowerCAmelCase : Tuple = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowerCAmelCase , lowerCAmelCase , rtol=1e-2 ) ) @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str ) -> int: """simple docstring""" return f'''gaussian_noise_s={seed}_shape={'_'.join([str(lowerCAmelCase ) for s in shape] )}.npy''' def SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase : Union[str, Any]=0 , lowerCAmelCase : Any=(4, 3, 5_12, 5_12) , lowerCAmelCase : Any=False ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = torch.floataa if fpaa else torch.floataa __lowerCAmelCase : Optional[int] = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCAmelCase , lowerCAmelCase ) ) ).to(lowerCAmelCase ).to(lowerCAmelCase ) return image def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase : Optional[Any]="CompVis/stable-diffusion-v1-4" , lowerCAmelCase : int=False ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = """fp16""" if fpaa else None __lowerCAmelCase : List[str] = torch.floataa if fpaa else torch.floataa __lowerCAmelCase : Dict = AutoencoderKL.from_pretrained( lowerCAmelCase , subfolder="""vae""" , torch_dtype=lowerCAmelCase , revision=lowerCAmelCase , ) model.to(lowerCAmelCase ).eval() return model def SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase : Tuple=0 ) -> Tuple: """simple docstring""" if torch_device == "mps": return torch.manual_seed(lowerCAmelCase ) return torch.Generator(device=lowerCAmelCase ).manual_seed(lowerCAmelCase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Dict ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Dict = self.get_sd_vae_model() __lowerCAmelCase : Optional[int] = self.get_sd_image(lowerCAmelCase ) __lowerCAmelCase : List[str] = self.get_generator(lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model(lowerCAmelCase , generator=lowerCAmelCase , sample_posterior=lowerCAmelCase ).sample assert sample.shape == image.shape __lowerCAmelCase : Any = sample[-1, -2:, -2:, :2].flatten().float().cpu() __lowerCAmelCase : List[str] = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Any: """simple docstring""" __lowerCAmelCase : List[Any] = self.get_sd_vae_model(fpaa=lowerCAmelCase ) __lowerCAmelCase : Tuple = self.get_sd_image(lowerCAmelCase , fpaa=lowerCAmelCase ) __lowerCAmelCase : Optional[int] = self.get_generator(lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Dict = model(lowerCAmelCase , generator=lowerCAmelCase , sample_posterior=lowerCAmelCase ).sample assert sample.shape == image.shape __lowerCAmelCase : List[str] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __lowerCAmelCase : Optional[int] = torch.tensor(lowerCAmelCase ) assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str] , lowerCAmelCase : Any ) -> str: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.get_sd_vae_model() __lowerCAmelCase : Optional[int] = self.get_sd_image(lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : List[Any] = model(lowerCAmelCase ).sample assert sample.shape == image.shape __lowerCAmelCase : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __lowerCAmelCase : str = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int ) -> str: """simple docstring""" __lowerCAmelCase : Dict = self.get_sd_vae_model() __lowerCAmelCase : Optional[Any] = self.get_sd_image(lowerCAmelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model.decode(lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] __lowerCAmelCase : Union[str, Any] = sample[-1, -2:, :2, -2:].flatten().cpu() __lowerCAmelCase : Tuple = torch.tensor(lowerCAmelCase ) assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Any ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Tuple = self.get_sd_vae_model(fpaa=lowerCAmelCase ) __lowerCAmelCase : str = self.get_sd_image(lowerCAmelCase , shape=(3, 4, 64, 64) , fpaa=lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Dict = model.decode(lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] __lowerCAmelCase : Any = sample[-1, -2:, :2, -2:].flatten().float().cpu() __lowerCAmelCase : Union[str, Any] = torch.tensor(lowerCAmelCase ) assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase : Any ) -> Any: """simple docstring""" __lowerCAmelCase : List[Any] = self.get_sd_vae_model(fpaa=lowerCAmelCase ) __lowerCAmelCase : Union[str, Any] = self.get_sd_image(lowerCAmelCase , shape=(3, 4, 64, 64) , fpaa=lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = model.decode(lowerCAmelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __lowerCAmelCase : int = model.decode(lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase : List[Any] ) -> Dict: """simple docstring""" __lowerCAmelCase : Optional[int] = self.get_sd_vae_model() __lowerCAmelCase : Optional[Any] = self.get_sd_image(lowerCAmelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model.decode(lowerCAmelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __lowerCAmelCase : Tuple = model.decode(lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase : int , lowerCAmelCase : List[Any] ) -> Any: """simple docstring""" __lowerCAmelCase : Optional[Any] = self.get_sd_vae_model() __lowerCAmelCase : List[str] = self.get_sd_image(lowerCAmelCase ) __lowerCAmelCase : Any = self.get_generator(lowerCAmelCase ) with torch.no_grad(): __lowerCAmelCase : Optional[int] = model.encode(lowerCAmelCase ).latent_dist __lowerCAmelCase : Union[str, Any] = dist.sample(generator=lowerCAmelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __lowerCAmelCase : Any = sample[0, -1, -3:, -3:].flatten().cpu() __lowerCAmelCase : int = torch.tensor(lowerCAmelCase ) __lowerCAmelCase : str = 3e-3 if torch_device != """mps""" else 1e-2 assert torch_all_close(lowerCAmelCase , lowerCAmelCase , atol=lowerCAmelCase )
139
1
from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transformers.training_args import ParallelMode from transformers.utils import logging __A = logging.get_logger(__name__) if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset from transformers import Trainer class _SCREAMING_SNAKE_CASE ( _lowercase ): '''simple docstring''' def __init__(self : List[Any] , UpperCAmelCase_ : int = 101) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =length def __len__(self : Dict) ->str: '''simple docstring''' return self.length def __getitem__(self : List[Any] , UpperCAmelCase_ : str) ->Optional[Any]: '''simple docstring''' return i class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __call__(self : str , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' return {"input_ids": torch.tensor(__lowerCAmelCase), "labels": torch.tensor(__lowerCAmelCase)} class _SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__(self : str) ->Dict: '''simple docstring''' super().__init__() # Add some (unused) params otherwise DDP will complain. lowerCamelCase__: List[Any] =nn.Linear(120 , 80) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str=None) ->Union[str, Any]: '''simple docstring''' if labels is not None: return torch.tensor(0.0 , device=input_ids.device), input_ids else: return input_ids class _SCREAMING_SNAKE_CASE ( _lowercase ): '''simple docstring''' @require_torch_neuroncore def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] =F"""--nproc_per_node=2 --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py """.split() lowerCamelCase__: int =self.get_auto_remove_tmp_dir() lowerCamelCase__: Optional[int] =F"""--output_dir {output_dir}""".split() lowerCamelCase__: int =['''torchrun'''] + distributed_args + args execute_subprocess_async(__lowerCAmelCase , env=self.get_env()) # successful return here == success - any errors would have caused an error in the sub-call class _SCREAMING_SNAKE_CASE ( _lowercase ): '''simple docstring''' @require_torch_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: int =F"""--nproc_per_node={torch.cuda.device_count()} --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py """.split() lowerCamelCase__: Optional[int] =self.get_auto_remove_tmp_dir() lowerCamelCase__: Tuple =F"""--output_dir {output_dir}""".split() lowerCamelCase__: str =['''torchrun'''] + distributed_args + args execute_subprocess_async(__lowerCAmelCase , env=self.get_env()) # successful return here == success - any errors would have caused an error in the sub-call if __name__ == "__main__": # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: # # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py __A = HfArgumentParser((TrainingArguments,)) __A = parser.parse_args_into_dataclasses()[0] logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, ' f'distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}' ) # Essentially, what we want to verify in the distributed case is that we get all samples back, # in the right order. (this is crucial for prediction for instance) for dataset_length in [101, 40, 7]: __A = DummyDataset(dataset_length) def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" lowerCamelCase__: str =list(range(len(A_ ) ) ) lowerCamelCase__: List[Any] =p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential if not success and training_args.local_rank == 0: logger.warning( "Predictions and/or labels do not match expected results:\n - predictions: " F"""{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}""" ) return {"success": success} __A = Trainer( model=DummyModel(), args=training_args, data_collator=DummyDataCollator(), eval_dataset=dataset, compute_metrics=compute_metrics, ) __A = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __A = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __A = 2 __A = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __A = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __A = None
10
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = {'''configuration_reformer''': ['''REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ReformerConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''ReformerTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''ReformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ReformerAttention''', '''ReformerForMaskedLM''', '''ReformerForQuestionAnswering''', '''ReformerForSequenceClassification''', '''ReformerLayer''', '''ReformerModel''', '''ReformerModelWithLMHead''', '''ReformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
0
"""simple docstring""" def lowercase_ ( _lowerCamelCase: int ) -> Dict: '''simple docstring''' __lowerCamelCase : list[list[int]] = [[0 for _ in range(_lowerCamelCase )] for _ in range(m + 1 )] for i in range(m + 1 ): __lowerCamelCase : Dict = 1 for n in range(m + 1 ): for k in range(1 , _lowerCamelCase ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: __A = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: __A = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
370
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __A = logging.get_logger(__name__) __A = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def lowercase_ ( _lowerCamelCase: str ) -> int: '''simple docstring''' for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: __lowerCamelCase : int = model_type_to_module_name(_lowerCamelCase ) __lowerCamelCase : Union[str, Any] = importlib.import_module(F""".{module_name}""" , "transformers.models" ) try: return getattr(_lowerCamelCase , _lowerCamelCase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(_lowerCamelCase , "__name__" , _lowerCamelCase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __lowerCamelCase : int = importlib.import_module("transformers" ) if hasattr(_lowerCamelCase , _lowerCamelCase ): return getattr(_lowerCamelCase , _lowerCamelCase ) return None def lowercase_ ( _lowerCamelCase: Union[str, os.PathLike] , _lowerCamelCase: Optional[Union[str, os.PathLike]] = None , _lowerCamelCase: bool = False , _lowerCamelCase: bool = False , _lowerCamelCase: Optional[Dict[str, str]] = None , _lowerCamelCase: Optional[Union[bool, str]] = None , _lowerCamelCase: Optional[str] = None , _lowerCamelCase: bool = False , **_lowerCamelCase: Tuple , ) -> List[str]: '''simple docstring''' __lowerCamelCase : List[str] = get_file_from_repo( _lowerCamelCase , _lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , resume_download=_lowerCamelCase , proxies=_lowerCamelCase , use_auth_token=_lowerCamelCase , revision=_lowerCamelCase , local_files_only=_lowerCamelCase , ) if resolved_config_file is None: logger.info( "Could not locate the image processor configuration file, will try to use the model config instead." ) return {} with open(_lowerCamelCase , encoding="utf-8" ) as reader: return json.load(_lowerCamelCase ) class _snake_case : def __init__( self : Tuple ): raise EnvironmentError( "AutoImageProcessor is designed to be instantiated " "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(UpperCAmelCase ) def lowerCamelCase__ ( cls : Dict , UpperCAmelCase : Optional[int] , **UpperCAmelCase : Any ): __lowerCamelCase : int = kwargs.pop("config" , UpperCAmelCase ) __lowerCamelCase : Dict = kwargs.pop("trust_remote_code" , UpperCAmelCase ) __lowerCamelCase : Any = True __lowerCamelCase , __lowerCamelCase : str = ImageProcessingMixin.get_image_processor_dict(UpperCAmelCase , **UpperCAmelCase ) __lowerCamelCase : Optional[int] = config_dict.get("image_processor_type" , UpperCAmelCase ) __lowerCamelCase : List[Any] = None if "AutoImageProcessor" in config_dict.get("auto_map" , {} ): __lowerCamelCase : List[str] = config_dict["auto_map"]["AutoImageProcessor"] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: __lowerCamelCase : Dict = config_dict.pop("feature_extractor_type" , UpperCAmelCase ) if feature_extractor_class is not None: logger.warning( "Could not find image processor class in the image processor config or the model config. Loading" " based on pattern matching with the model's feature extractor configuration." ) __lowerCamelCase : Tuple = feature_extractor_class.replace("FeatureExtractor" , "ImageProcessor" ) if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): __lowerCamelCase : Any = config_dict["auto_map"]["AutoFeatureExtractor"] __lowerCamelCase : Optional[int] = feature_extractor_auto_map.replace("FeatureExtractor" , "ImageProcessor" ) logger.warning( "Could not find image processor auto map in the image processor config or the model config." " Loading based on pattern matching with the model's feature extractor configuration." ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(UpperCAmelCase , UpperCAmelCase ): __lowerCamelCase : int = AutoConfig.from_pretrained(UpperCAmelCase , **UpperCAmelCase ) # It could be in `config.image_processor_type`` __lowerCamelCase : int = getattr(UpperCAmelCase , "image_processor_type" , UpperCAmelCase ) if hasattr(UpperCAmelCase , "auto_map" ) and "AutoImageProcessor" in config.auto_map: __lowerCamelCase : Optional[int] = config.auto_map["AutoImageProcessor"] if image_processor_class is not None: __lowerCamelCase : Any = image_processor_class_from_name(UpperCAmelCase ) __lowerCamelCase : str = image_processor_auto_map is not None __lowerCamelCase : Optional[Any] = image_processor_class is not None or type(UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING __lowerCamelCase : Dict = resolve_trust_remote_code( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if has_remote_code and trust_remote_code: __lowerCamelCase : Optional[Any] = get_class_from_dynamic_module( UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) __lowerCamelCase : List[Any] = kwargs.pop("code_revision" , UpperCAmelCase ) if os.path.isdir(UpperCAmelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(UpperCAmelCase , **UpperCAmelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(UpperCAmelCase , **UpperCAmelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING: __lowerCamelCase : Tuple = IMAGE_PROCESSOR_MAPPING[type(UpperCAmelCase )] return image_processor_class.from_dict(UpperCAmelCase , **UpperCAmelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def lowerCamelCase__ ( UpperCAmelCase : Any , UpperCAmelCase : Union[str, Any] ): IMAGE_PROCESSOR_MAPPING.register(UpperCAmelCase , UpperCAmelCase )
64
0
from __future__ import annotations __A : List[str] = 10 def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> list[int]: '''simple docstring''' lowerCAmelCase : Union[str, Any] = 1 lowerCAmelCase : List[Any] = max(SCREAMING_SNAKE_CASE__ ) while placement <= max_digit: # declare and initialize empty buckets lowerCAmelCase : list[list] = [[] for _ in range(SCREAMING_SNAKE_CASE__ )] # split list_of_ints between the buckets for i in list_of_ints: lowerCAmelCase : int = int((i / placement) % RADIX ) buckets[tmp].append(SCREAMING_SNAKE_CASE__ ) # put each buckets' contents into list_of_ints lowerCAmelCase : Tuple = 0 for b in range(SCREAMING_SNAKE_CASE__ ): for i in buckets[b]: lowerCAmelCase : List[str] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
138
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets snake_case_ : Union[str, Any] = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" snake_case_ : int = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" snake_case_ : Optional[Any] = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: return float((preds == labels).mean() ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Union[str, Any]: UpperCAmelCase_ : str = simple_accuracy(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = float(fa_score(y_true=SCREAMING_SNAKE_CASE__, y_pred=SCREAMING_SNAKE_CASE__ ) ) return { "accuracy": acc, "f1": fa, } def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : str ) -> Dict: UpperCAmelCase_ : Optional[int] = float(pearsonr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )[0] ) UpperCAmelCase_ : str = float(spearmanr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __a (datasets.Metric ): def UpperCAmelCase__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] ) -> List[Any]: """simple docstring""" if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__magic_name__ , __magic_name__ )} elif self.config_name == "stsb": return pearson_and_spearman(__magic_name__ , __magic_name__ ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__magic_name__ , __magic_name__ ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__magic_name__ , __magic_name__ )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
125
0
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder __SCREAMING_SNAKE_CASE : int = 'base_with_context' def snake_case (__lowercase , __lowercase ) -> Optional[int]: '''simple docstring''' _snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights["token_embedder"]["embedding"] ) ) _snake_case : Optional[int] = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCAmelCase ) for lyr_num, lyr in enumerate(model.encoders ): _snake_case : Union[str, Any] = weights[F"""layers_{lyr_num}"""] _snake_case : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) _snake_case : List[Any] = ly_weight["""attention"""] _snake_case : int = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _snake_case : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _snake_case : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _snake_case : Optional[int] = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def snake_case (__lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' _snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights["input_proj"]["kernel"].T ) ) _snake_case : int = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCAmelCase ) for lyr_num, lyr in enumerate(model.encoders ): _snake_case : Union[str, Any] = weights[F"""layers_{lyr_num}"""] _snake_case : Tuple = ly_weight["""attention"""] _snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _snake_case : int = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _snake_case : Any = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) _snake_case : int = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _snake_case : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _snake_case : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _snake_case : Optional[int] = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def snake_case (__lowercase , __lowercase ) -> List[Any]: '''simple docstring''' _snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(weights["time_emb_dense0"]["kernel"].T ) ) _snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights["time_emb_dense1"]["kernel"].T ) ) _snake_case : Optional[Any] = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCAmelCase ) _snake_case : int = nn.Parameter( torch.FloatTensor(weights["continuous_inputs_projection"]["kernel"].T ) ) for lyr_num, lyr in enumerate(model.decoders ): _snake_case : int = weights[F"""layers_{lyr_num}"""] _snake_case : int = nn.Parameter( torch.FloatTensor(ly_weight["pre_self_attention_layer_norm"]["scale"] ) ) _snake_case : Any = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_0"]["DenseGeneral_0"]["kernel"].T ) ) _snake_case : Optional[Any] = ly_weight["""self_attention"""] _snake_case : int = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _snake_case : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _snake_case : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _snake_case : str = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _snake_case : str = ly_weight["""MultiHeadDotProductAttention_0"""] _snake_case : int = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _snake_case : str = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _snake_case : Any = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _snake_case : Optional[int] = nn.Parameter( torch.FloatTensor(ly_weight["pre_cross_attention_layer_norm"]["scale"] ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _snake_case : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_1"]["DenseGeneral_0"]["kernel"].T ) ) _snake_case : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _snake_case : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _snake_case : int = nn.Parameter(torch.FloatTensor(weights["decoder_norm"]["scale"] ) ) _snake_case : Tuple = nn.Parameter(torch.FloatTensor(weights["spec_out_dense"]["kernel"].T ) ) return model def snake_case (__lowercase ) -> Optional[Any]: '''simple docstring''' _snake_case : str = checkpoints.load_tax_checkpoint(args.checkpoint_path ) _snake_case : List[Any] = jnp.tree_util.tree_map(onp.array , _lowerCAmelCase ) _snake_case : Dict = [ """from __gin__ import dynamic_registration""", """from music_spectrogram_diffusion.models.diffusion import diffusion_utils""", """diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""", """diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""", ] _snake_case : Optional[Any] = os.path.join(args.checkpoint_path , ".." , "config.gin" ) _snake_case : List[str] = inference.parse_training_gin_file(_lowerCAmelCase , _lowerCAmelCase ) _snake_case : Dict = inference.InferenceModel(args.checkpoint_path , _lowerCAmelCase ) _snake_case : Optional[int] = DDPMScheduler(beta_schedule="squaredcos_cap_v2" , variance_type="fixed_large" ) _snake_case : Any = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["inputs"] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) _snake_case : Dict = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["targets_context"] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) _snake_case : List[Any] = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["targets_context"] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) _snake_case : int = load_notes_encoder(ta_checkpoint["target"]["token_encoder"] , _lowerCAmelCase ) _snake_case : Union[str, Any] = load_continuous_encoder(ta_checkpoint["target"]["continuous_encoder"] , _lowerCAmelCase ) _snake_case : Any = load_decoder(ta_checkpoint["target"]["decoder"] , _lowerCAmelCase ) _snake_case : Tuple = OnnxRuntimeModel.from_pretrained("kashif/soundstream_mel_decoder" ) _snake_case : Tuple = SpectrogramDiffusionPipeline( notes_encoder=_lowerCAmelCase , continuous_encoder=_lowerCAmelCase , decoder=_lowerCAmelCase , scheduler=_lowerCAmelCase , melgan=_lowerCAmelCase , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() parser.add_argument('--output_path', default=None, type=str, required=True, help='Path to the converted model.') parser.add_argument( '--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.' ) parser.add_argument( '--checkpoint_path', default=F'''{MODEL}/checkpoint_500000''', type=str, required=False, help='Path to the original jax model checkpoint.', ) __SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() main(args)
371
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def snake_case (__lowercase ) -> str: '''simple docstring''' _snake_case : int = args.pruning_method _snake_case : List[Any] = args.threshold _snake_case : Optional[Any] = args.model_name_or_path.rstrip("/" ) _snake_case : List[str] = args.target_model_path print(F"""Load fine-pruned model from {model_name_or_path}""" ) _snake_case : List[Any] = torch.load(os.path.join(__lowercase , "pytorch_model.bin" ) ) _snake_case : List[str] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: _snake_case : Tuple = tensor print(F"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: _snake_case : Optional[int] = tensor print(F"""Copied layer {name}""" ) elif "bias" in name: _snake_case : List[Any] = tensor print(F"""Copied layer {name}""" ) else: if pruning_method == "magnitude": _snake_case : Tuple = MagnitudeBinarizer.apply(inputs=__lowercase , threshold=__lowercase ) _snake_case : List[str] = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue _snake_case : Optional[Any] = name[:-6] _snake_case : Any = model[F"""{prefix_}mask_scores"""] _snake_case : Tuple = TopKBinarizer.apply(__lowercase , __lowercase ) _snake_case : Optional[Any] = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue _snake_case : int = name[:-6] _snake_case : List[Any] = model[F"""{prefix_}mask_scores"""] _snake_case : List[str] = ThresholdBinarizer.apply(__lowercase , __lowercase , __lowercase ) _snake_case : List[str] = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue _snake_case : int = name[:-6] _snake_case : Any = model[F"""{prefix_}mask_scores"""] _snake_case ,_snake_case : Union[str, Any] = -0.1, 1.1 _snake_case : Dict = torch.sigmoid(__lowercase ) _snake_case : List[str] = s * (r - l) + l _snake_case : Tuple = s_bar.clamp(min=0.0 , max=1.0 ) _snake_case : Union[str, Any] = tensor * mask print(F"""Pruned layer {name}""" ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: _snake_case : Any = os.path.join( os.path.dirname(__lowercase ) , F"""bertarized_{os.path.basename(__lowercase )}""" ) if not os.path.isdir(__lowercase ): shutil.copytree(__lowercase , __lowercase ) print(F"""\nCreated folder {target_model_path}""" ) torch.save(__lowercase , os.path.join(__lowercase , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[Any] = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) __SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
284
0
import pprint import requests A_ :Dict = '''https://zenquotes.io/api''' def A ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def A ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ :str = random_quotes() pprint.pprint(response)
71
A_ :str = '''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
71
1
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Optional[int] = (KDPMaDiscreteScheduler,) UpperCAmelCase__ : Dict = 10 def snake_case_ ( self, **SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase : str = { 'num_train_timesteps': 1100, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**SCREAMING_SNAKE_CASE_ ) return config def snake_case_ ( self ) -> str: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> List[str]: for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01], [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_, beta_end=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Tuple: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Any: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : Optional[Any] = self.scheduler_classes[0] UpperCamelCase : List[str] = self.get_scheduler_config(prediction_type='v_prediction' ) UpperCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCamelCase : int = self.dummy_model() UpperCamelCase : str = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCamelCase : Optional[int] = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): UpperCamelCase : List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = output.prev_sample UpperCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934e-07 ) < 1e-2 assert abs(result_mean.item() - 6.1112e-10 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.693428650170972e-07 ) < 1e-2 assert abs(result_mean.item() - 0.00_02 ) < 1e-3 def snake_case_ ( self ) -> Any: if torch_device == "mps": return UpperCamelCase : Optional[int] = self.scheduler_classes[0] UpperCamelCase : List[Any] = self.get_scheduler_config() UpperCamelCase : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCamelCase : Dict = self.dummy_model() UpperCamelCase : Any = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCamelCase : Union[str, Any] = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): UpperCamelCase : Optional[int] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = scheduler.step(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.prev_sample UpperCamelCase : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 def snake_case_ ( self ) -> Dict: if torch_device == "mps": return UpperCamelCase : Union[str, Any] = self.scheduler_classes[0] UpperCamelCase : int = self.get_scheduler_config() UpperCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps, device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.dummy_model() UpperCamelCase : int = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: UpperCamelCase : Tuple = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = scheduler.step(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.prev_sample UpperCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if str(SCREAMING_SNAKE_CASE_ ).startswith('cpu' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3
103
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version __UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') __UpperCAmelCase = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) __UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase_ : UpperCAmelCase__ : Optional[str] = field( default="cifar10" , metadata={"help": "Name of a dataset from the datasets package"} ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."} , ) UpperCAmelCase__ : Optional[str] = field(default=a__ , metadata={"help": "A folder containing the training data."} ) UpperCAmelCase__ : Optional[str] = field(default=a__ , metadata={"help": "A folder containing the validation data."} ) UpperCAmelCase__ : Optional[float] = field( default=0.15 , metadata={"help": "Percent to split off of train for validation."} ) UpperCAmelCase__ : int = field(default=32 , metadata={"help": "The size of the square patches to use for masking."} ) UpperCAmelCase__ : float = field( default=0.6 , metadata={"help": "Percentage of patches to mask."} , ) UpperCAmelCase__ : Optional[int] = field( default=a__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) UpperCAmelCase__ : Optional[int] = field( default=a__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : List[Any] = {} if self.train_dir is not None: UpperCamelCase : Any = self.train_dir if self.validation_dir is not None: UpperCamelCase : Union[str, Any] = self.validation_dir UpperCamelCase : List[str] = data_files if data_files else None @dataclass class lowerCAmelCase_ : UpperCAmelCase__ : str = field( default=a__ , metadata={ "help": ( "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a " "checkpoint identifier on the hub. " "Don't set if you want to train a model from scratch." ) } , ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(a__ )} , ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) UpperCAmelCase__ : Optional[str] = field( default=a__ , metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"} , ) UpperCAmelCase__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) UpperCAmelCase__ : str = field(default=a__ , metadata={"help": "Name or path of preprocessor config."} ) UpperCAmelCase__ : bool = field( default=a__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) UpperCAmelCase__ : Optional[int] = field( default=a__ , metadata={ "help": ( "The size (resolution) of each image. If not specified, will use `image_size` of the configuration." ) } , ) UpperCAmelCase__ : Optional[int] = field( default=a__ , metadata={ "help": ( "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration." ) } , ) UpperCAmelCase__ : Optional[int] = field( default=a__ , metadata={"help": "Stride to use for the encoder."} , ) class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_=192, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=0.6 ) -> Optional[Any]: UpperCamelCase : List[Any] = input_size UpperCamelCase : Any = mask_patch_size UpperCamelCase : Tuple = model_patch_size UpperCamelCase : Optional[Any] = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('Input size must be divisible by mask patch size' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('Mask patch size must be divisible by model patch size' ) UpperCamelCase : Tuple = self.input_size // self.mask_patch_size UpperCamelCase : int = self.mask_patch_size // self.model_patch_size UpperCamelCase : Union[str, Any] = self.rand_size**2 UpperCamelCase : str = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self ) -> str: UpperCamelCase : Union[str, Any] = np.random.permutation(self.token_count )[: self.mask_count] UpperCamelCase : Tuple = np.zeros(self.token_count, dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = 1 UpperCamelCase : Union[str, Any] = mask.reshape((self.rand_size, self.rand_size) ) UpperCamelCase : str = mask.repeat(self.scale, axis=0 ).repeat(self.scale, axis=1 ) return torch.tensor(mask.flatten() ) def UpperCamelCase ( snake_case__ : int ) -> int: UpperCamelCase : List[Any] = torch.stack([example['pixel_values'] for example in examples] ) UpperCamelCase : Optional[Any] = torch.stack([example['mask'] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def UpperCamelCase ( ) -> Optional[int]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCamelCase : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCamelCase , UpperCamelCase , UpperCamelCase : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase , UpperCamelCase , UpperCamelCase : Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mim' , snake_case__ , snake_case__ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCamelCase : Optional[int] = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. UpperCamelCase : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. UpperCamelCase : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. UpperCamelCase : Tuple = None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case__ ) and data_args.train_val_split > 0.0: UpperCamelCase : List[str] = ds['train'].train_test_split(data_args.train_val_split ) UpperCamelCase : str = split['train'] UpperCamelCase : Any = split['test'] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase : Tuple = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: UpperCamelCase : Dict = AutoConfig.from_pretrained(model_args.config_name_or_path , **snake_case__ ) elif model_args.model_name_or_path: UpperCamelCase : Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , **snake_case__ ) else: UpperCamelCase : str = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(F"""New config: {config}""" ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(snake_case__ , 'decoder_type' ): UpperCamelCase : Tuple = 'simmim' # adapt config UpperCamelCase : List[str] = model_args.image_size if model_args.image_size is not None else config.image_size UpperCamelCase : str = model_args.patch_size if model_args.patch_size is not None else config.patch_size UpperCamelCase : Dict = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { 'image_size': model_args.image_size, 'patch_size': model_args.patch_size, 'encoder_stride': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: UpperCamelCase : Optional[Any] = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **snake_case__ ) elif model_args.model_name_or_path: UpperCamelCase : List[Any] = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **snake_case__ ) else: UpperCamelCase : Optional[int] = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } UpperCamelCase : Dict = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: UpperCamelCase : Union[str, Any] = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=snake_case__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) UpperCamelCase : Union[str, Any] = AutoModelForMaskedImageModeling.from_config(snake_case__ ) if training_args.do_train: UpperCamelCase : Optional[int] = ds['train'].column_names else: UpperCamelCase : Optional[int] = ds['validation'].column_names if data_args.image_column_name is not None: UpperCamelCase : Dict = data_args.image_column_name elif "image" in column_names: UpperCamelCase : Union[str, Any] = 'image' elif "img" in column_names: UpperCamelCase : int = 'img' else: UpperCamelCase : Optional[int] = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py UpperCamelCase : Optional[int] = Compose( [ Lambda(lambda snake_case__ : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator UpperCamelCase : Optional[int] = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(snake_case__ : List[Any] ): UpperCamelCase : Any = [transforms(snake_case__ ) for image in examples[image_column_name]] UpperCamelCase : Tuple = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: UpperCamelCase : Tuple = ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: UpperCamelCase : str = ( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case__ ) # Initialize our trainer UpperCamelCase : Any = Trainer( model=snake_case__ , args=snake_case__ , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=snake_case__ , data_collator=snake_case__ , ) # Training if training_args.do_train: UpperCamelCase : Dict = None if training_args.resume_from_checkpoint is not None: UpperCamelCase : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCamelCase : Tuple = last_checkpoint UpperCamelCase : List[Any] = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCamelCase : List[str] = trainer.evaluate() trainer.log_metrics('eval' , snake_case__ ) trainer.save_metrics('eval' , snake_case__ ) # Write model card and (optionally) push to hub UpperCamelCase : List[str] = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'masked-image-modeling', 'dataset': data_args.dataset_name, 'tags': ['masked-image-modeling'], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) if __name__ == "__main__": main()
103
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case : Dict = { "configuration_biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig"], "tokenization_biogpt": ["BioGptTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Optional[Any] = [ "BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "BioGptForCausalLM", "BioGptForTokenClassification", "BioGptForSequenceClassification", "BioGptModel", "BioGptPreTrainedModel", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys snake_case : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
281
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
1
"""simple docstring""" import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig a_ = logging.get_logger(__name__) # General docstring a_ = "PoolFormerConfig" # Base docstring a_ = "sail/poolformer_s12" a_ = [1, 5_12, 7, 7] # Image classification docstring a_ = "sail/poolformer_s12" a_ = "tabby, tabby cat" a_ = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def a__ ( __lowercase , __lowercase = 0.0 , __lowercase = False ) -> Dict: if drop_prob == 0.0 or not training: return input _A = 1 - drop_prob _A = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _A = keep_prob + torch.rand(__lowercase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _A = input.div(__lowercase ) * random_tensor return output class snake_case ( nn.Module): def __init__( self : Any , a__ : Optional[float] = None ) -> None: '''simple docstring''' super().__init__() _A = drop_prob def a_ ( self : Optional[Any] , a__ : torch.Tensor ) -> torch.Tensor: '''simple docstring''' return drop_path(a__ , self.drop_prob , self.training ) def a_ ( self : List[str] ) -> str: '''simple docstring''' return "p={}".format(self.drop_prob ) class snake_case ( nn.Module): def __init__( self : Union[str, Any] , a__ : List[Any] , a__ : Any , a__ : List[Any] , a__ : Optional[int] , a__ : Dict , a__ : str=None ) -> Optional[Any]: '''simple docstring''' super().__init__() _A = patch_size if isinstance(a__ , collections.abc.Iterable ) else (patch_size, patch_size) _A = stride if isinstance(a__ , collections.abc.Iterable ) else (stride, stride) _A = padding if isinstance(a__ , collections.abc.Iterable ) else (padding, padding) _A = nn.Convad(a__ , a__ , kernel_size=a__ , stride=a__ , padding=a__ ) _A = norm_layer(a__ ) if norm_layer else nn.Identity() def a_ ( self : Dict , a__ : Any ) -> List[str]: '''simple docstring''' _A = self.projection(a__ ) _A = self.norm(a__ ) return embeddings class snake_case ( nn.GroupNorm): def __init__( self : Dict , a__ : Optional[int] , **a__ : Dict ) -> Optional[Any]: '''simple docstring''' super().__init__(1 , a__ , **a__ ) class snake_case ( nn.Module): def __init__( self : int , a__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' super().__init__() _A = nn.AvgPoolad(a__ , stride=1 , padding=pool_size // 2 , count_include_pad=a__ ) def a_ ( self : List[str] , a__ : int ) -> str: '''simple docstring''' return self.pool(a__ ) - hidden_states class snake_case ( nn.Module): def __init__( self : Tuple , a__ : Optional[int] , a__ : Optional[Any] , a__ : List[str] , a__ : Optional[int] ) -> Any: '''simple docstring''' super().__init__() _A = nn.Convad(a__ , a__ , 1 ) _A = nn.Convad(a__ , a__ , 1 ) _A = PoolFormerDropPath(a__ ) if isinstance(config.hidden_act , a__ ): _A = ACTaFN[config.hidden_act] else: _A = config.hidden_act def a_ ( self : List[Any] , a__ : int ) -> Dict: '''simple docstring''' _A = self.conva(a__ ) _A = self.act_fn(a__ ) _A = self.drop(a__ ) _A = self.conva(a__ ) _A = self.drop(a__ ) return hidden_states class snake_case ( nn.Module): def __init__( self : Union[str, Any] , a__ : str , a__ : List[str] , a__ : List[Any] , a__ : List[str] , a__ : Optional[Any] , a__ : Tuple ) -> Dict: '''simple docstring''' super().__init__() _A = PoolFormerPooling(a__ ) _A = PoolFormerOutput(a__ , a__ , a__ , a__ ) _A = PoolFormerGroupNorm(a__ ) _A = PoolFormerGroupNorm(a__ ) # Useful for training neural nets _A = PoolFormerDropPath(a__ ) if drop_path > 0.0 else nn.Identity() _A = config.use_layer_scale if config.use_layer_scale: _A = nn.Parameter( config.layer_scale_init_value * torch.ones((a__) ) , requires_grad=a__ ) _A = nn.Parameter( config.layer_scale_init_value * torch.ones((a__) ) , requires_grad=a__ ) def a_ ( self : Union[str, Any] , a__ : Optional[int] ) -> Tuple: '''simple docstring''' if self.use_layer_scale: _A = self.pooling(self.before_norm(a__ ) ) _A = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _A = hidden_states + self.drop_path(a__ ) _A = () _A = self.output(self.after_norm(a__ ) ) _A = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _A = hidden_states + self.drop_path(a__ ) _A = (output,) + outputs return outputs else: _A = self.drop_path(self.pooling(self.before_norm(a__ ) ) ) # First residual connection _A = pooling_output + hidden_states _A = () # Second residual connection inside the PoolFormerOutput block _A = self.drop_path(self.output(self.after_norm(a__ ) ) ) _A = hidden_states + layer_output _A = (output,) + outputs return outputs class snake_case ( nn.Module): def __init__( self : str , a__ : int ) -> Any: '''simple docstring''' super().__init__() _A = config # stochastic depth decay rule _A = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _A = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _A = nn.ModuleList(a__ ) # Transformer blocks _A = [] _A = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _A = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( a__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(a__ ) ) _A = nn.ModuleList(a__ ) def a_ ( self : Tuple , a__ : Union[str, Any] , a__ : Tuple=False , a__ : List[str]=True ) -> List[Any]: '''simple docstring''' _A = () if output_hidden_states else None _A = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _A , _A = layers # Get patch embeddings from hidden_states _A = embedding_layer(a__ ) # Send the embeddings through the blocks for _, blk in enumerate(a__ ): _A = blk(a__ ) _A = layer_outputs[0] if output_hidden_states: _A = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=a__ , hidden_states=a__ ) class snake_case ( _UpperCamelCase): __UpperCamelCase = PoolFormerConfig __UpperCamelCase = 'poolformer' __UpperCamelCase = 'pixel_values' __UpperCamelCase = True def a_ ( self : Tuple , a__ : Dict ) -> Any: '''simple docstring''' if isinstance(a__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(a__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def a_ ( self : int , a__ : Dict , a__ : int=False ) -> str: '''simple docstring''' if isinstance(a__ , a__ ): _A = value a_ = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" a_ = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( 'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , _UpperCamelCase , ) class snake_case ( _UpperCamelCase): def __init__( self : int , a__ : Dict ) -> str: '''simple docstring''' super().__init__(a__ ) _A = config _A = PoolFormerEncoder(a__ ) # Initialize weights and apply final processing self.post_init() def a_ ( self : Union[str, Any] ) -> str: '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def a_ ( self : Tuple , a__ : Optional[torch.FloatTensor] = None , a__ : Optional[bool] = None , a__ : Optional[bool] = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: '''simple docstring''' _A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _A = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("You have to specify pixel_values" ) _A = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ , ) _A = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=a__ , hidden_states=encoder_outputs.hidden_states , ) class snake_case ( nn.Module): def __init__( self : List[str] , a__ : Dict ) -> Optional[Any]: '''simple docstring''' super().__init__() _A = nn.Linear(config.hidden_size , config.hidden_size ) def a_ ( self : int , a__ : Tuple ) -> str: '''simple docstring''' _A = self.dense(a__ ) return output @add_start_docstrings( '\n PoolFormer Model transformer with an image classification head on top\n ' , _UpperCamelCase , ) class snake_case ( _UpperCamelCase): def __init__( self : Tuple , a__ : str ) -> Optional[int]: '''simple docstring''' super().__init__(a__ ) _A = config.num_labels _A = PoolFormerModel(a__ ) # Final norm _A = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _A = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def a_ ( self : int , a__ : Optional[torch.FloatTensor] = None , a__ : Optional[torch.LongTensor] = None , a__ : Optional[bool] = None , a__ : Optional[bool] = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: '''simple docstring''' _A = return_dict if return_dict is not None else self.config.use_return_dict _A = self.poolformer( a__ , output_hidden_states=a__ , return_dict=a__ , ) _A = outputs[0] _A = self.classifier(self.norm(a__ ).mean([-2, -1] ) ) _A = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _A = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _A = "single_label_classification" else: _A = "multi_label_classification" if self.config.problem_type == "regression": _A = MSELoss() if self.num_labels == 1: _A = loss_fct(logits.squeeze() , labels.squeeze() ) else: _A = loss_fct(a__ , a__ ) elif self.config.problem_type == "single_label_classification": _A = CrossEntropyLoss() _A = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _A = BCEWithLogitsLoss() _A = loss_fct(a__ , a__ ) if not return_dict: _A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states )
163
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase): __UpperCamelCase = StableDiffusionInstructPixaPixPipeline __UpperCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} __UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def a_ ( self : Optional[int] ) -> str: '''simple docstring''' torch.manual_seed(0 ) _A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) _A = PNDMScheduler(skip_prk_steps=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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) _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 a_ ( self : Optional[Any] , a__ : Dict , a__ : Tuple=0 ) -> Union[str, Any]: '''simple docstring''' _A = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) _A = image.cpu().permute(0 , 2 , 3 , 1 )[0] _A = Image.fromarray(np.uinta(a__ ) ).convert("RGB" ) if str(a__ ).startswith("mps" ): _A = torch.manual_seed(a__ ) else: _A = torch.Generator(device=a__ ).manual_seed(a__ ) _A = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "image_guidance_scale": 1, "output_type": "numpy", } return inputs def a_ ( self : Dict ) -> str: '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionInstructPixaPixPipeline(**a__ ) _A = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) _A = self.get_dummy_inputs(a__ ) _A = sd_pipe(**a__ ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def a_ ( self : str ) -> Optional[int]: '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionInstructPixaPixPipeline(**a__ ) _A = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) _A = self.get_dummy_inputs(a__ ) _A = "french fries" _A = sd_pipe(**a__ , negative_prompt=a__ ) _A = output.images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def a_ ( self : Optional[int] ) -> int: '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionInstructPixaPixPipeline(**a__ ) _A = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) _A = self.get_dummy_inputs(a__ ) _A = [inputs["prompt"]] * 2 _A = np.array(inputs["image"] ).astype(np.floataa ) / 2_5_5.0 _A = torch.from_numpy(a__ ).unsqueeze(0 ).to(a__ ) _A = image / 2 + 0.5 _A = image.permute(0 , 3 , 1 , 2 ) _A = image.repeat(2 , 1 , 1 , 1 ) _A = sd_pipe(**a__ ).images _A = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) _A = np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def a_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" ) _A = StableDiffusionInstructPixaPixPipeline(**a__ ) _A = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) _A = self.get_dummy_inputs(a__ ) _A = sd_pipe(**a__ ).images _A = image[0, -3:, -3:, -1] _A = [round(a__ , 4 ) for x in image_slice.flatten().tolist()] print(",".join([str(a__ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) _A = np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def a_ ( self : List[str] ) -> int: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def a_ ( self : str ) -> Any: '''simple docstring''' _A = self.get_dummy_components() _A = StableDiffusionInstructPixaPixPipeline(**a__ ) _A = VaeImageProcessor(do_resize=a__ , do_normalize=a__ ) _A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _A = pipe(**self.get_dummy_inputs_by_type(a__ , input_image_type="pt" ) )[0] _A = components["vae"] _A = self.get_dummy_inputs_by_type(a__ , input_image_type="pt" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): _A = vae.encode(inputs[image_param] ).latent_dist.mode() _A = pipe(**a__ )[0] _A = np.abs(out - out_latents_inputs ).max() self.assertLess(a__ , 1E-4 , "passing latents as image input generate different result from passing image" ) @slow @require_torch_gpu class snake_case ( unittest.TestCase): def a_ ( self : List[str] ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self : Optional[Any] , a__ : str=0 ) -> List[Any]: '''simple docstring''' _A = torch.manual_seed(a__ ) _A = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg" ) _A = { "prompt": "turn him into a cyborg", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "image_guidance_scale": 1.0, "output_type": "numpy", } return inputs def a_ ( self : List[Any] ) -> Any: '''simple docstring''' _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() _A = self.get_inputs() _A = pipe(**a__ ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) _A = np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def a_ ( self : List[Any] ) -> Any: '''simple docstring''' _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=a__ ) _A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() _A = self.get_inputs() _A = pipe(**a__ ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) _A = np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def a_ ( self : Union[str, Any] ) -> int: '''simple docstring''' _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=a__ ) _A = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() _A = self.get_inputs() _A = pipe(**a__ ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) _A = np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def a_ ( self : Optional[int] ) -> Dict: '''simple docstring''' _A = 0 def callback_fn(a__ : int , a__ : int , a__ : torch.FloatTensor ) -> None: _A = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _A = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) _A = latents[0, -3:, -3:, -1] _A = np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: _A = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) _A = latents[0, -3:, -3:, -1] _A = np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 _A = False _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=a__ , torch_dtype=torch.floataa ) _A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() _A = self.get_inputs() pipe(**a__ , callback=a__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def a_ ( self : List[Any] ) -> Any: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=a__ , torch_dtype=torch.floataa ) _A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _A = self.get_inputs() _A = pipe(**a__ ) _A = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def a_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' _A = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 _A = inputs["image"].resize((5_04, 5_04) ) _A = "timbrooks/instruct-pix2pix" _A = StableDiffusionInstructPixaPixPipeline.from_pretrained( a__ , safety_checker=a__ , ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() _A = pipe(**a__ ) _A = output.images[0] _A = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 5_04, 3) _A = np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3
163
1
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class _lowerCAmelCase ( __A ): """simple docstring""" lowerCamelCase = 42 @flax_register_to_config class _lowerCAmelCase ( nn.Module, __A, __A ): """simple docstring""" lowerCamelCase = 32 lowerCamelCase = 4 lowerCamelCase = 4 lowerCamelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowerCamelCase = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") lowerCamelCase = False lowerCamelCase = (320, 640, 1280, 1280) lowerCamelCase = 2 lowerCamelCase = 8 lowerCamelCase = None lowerCamelCase = 1280 lowerCamelCase = 0.0 lowerCamelCase = False lowerCamelCase = jnp.floataa lowerCamelCase = True lowerCamelCase = 0 lowerCamelCase = False def UpperCAmelCase_ ( self , _lowerCamelCase ) -> FrozenDict: # init input tensors A_ : List[str] = (1, self.in_channels, self.sample_size, self.sample_size) A_ : Optional[Any] = jnp.zeros(_lowerCamelCase , dtype=jnp.floataa ) A_ : str = jnp.ones((1,) , dtype=jnp.intaa ) A_ : Dict = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) A_ , A_ : int = jax.random.split(_lowerCamelCase ) A_ : Dict = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )["params"] def UpperCAmelCase_ ( self ) -> List[Any]: A_ : str = self.block_out_channels A_ : Optional[int] = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. A_ : List[str] = self.num_attention_heads or self.attention_head_dim # input A_ : Optional[Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time A_ : Dict = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) A_ : Optional[int] = FlaxTimestepEmbedding(_lowerCamelCase , dtype=self.dtype ) A_ : str = self.only_cross_attention if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ : int = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ : Any = (num_attention_heads,) * len(self.down_block_types ) # down A_ : List[Any] = [] A_ : str = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): A_ : int = output_channel A_ : Tuple = block_out_channels[i] A_ : str = i == len(_lowerCamelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": A_ : Dict = FlaxCrossAttnDownBlockaD( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: A_ : List[Any] = FlaxDownBlockaD( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_lowerCamelCase ) A_ : Any = down_blocks # mid A_ : str = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up A_ : Any = [] A_ : str = list(reversed(_lowerCamelCase ) ) A_ : int = list(reversed(_lowerCamelCase ) ) A_ : Dict = list(reversed(_lowerCamelCase ) ) A_ : Union[str, Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): A_ : List[str] = output_channel A_ : List[Any] = reversed_block_out_channels[i] A_ : List[Any] = reversed_block_out_channels[min(i + 1 , len(_lowerCamelCase ) - 1 )] A_ : List[Any] = i == len(_lowerCamelCase ) - 1 if up_block_type == "CrossAttnUpBlock2D": A_ : int = FlaxCrossAttnUpBlockaD( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , prev_output_channel=_lowerCamelCase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: A_ : Dict = FlaxUpBlockaD( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , prev_output_channel=_lowerCamelCase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_lowerCamelCase ) A_ : str = output_channel A_ : str = up_blocks # out A_ : List[Any] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) A_ : str = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase = True , _lowerCamelCase = False , ) -> Union[FlaxUNetaDConditionOutput, Tuple]: # 1. time if not isinstance(_lowerCamelCase , jnp.ndarray ): A_ : List[Any] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_lowerCamelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: A_ : Dict = timesteps.astype(dtype=jnp.floataa ) A_ : str = jnp.expand_dims(_lowerCamelCase , 0 ) A_ : List[str] = self.time_proj(_lowerCamelCase ) A_ : List[Any] = self.time_embedding(_lowerCamelCase ) # 2. pre-process A_ : str = jnp.transpose(_lowerCamelCase , (0, 2, 3, 1) ) A_ : Dict = self.conv_in(_lowerCamelCase ) # 3. down A_ : Optional[Any] = (sample,) for down_block in self.down_blocks: if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ , A_ : Tuple = down_block(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , deterministic=not train ) else: A_ , A_ : List[str] = down_block(_lowerCamelCase , _lowerCamelCase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: A_ : Optional[Any] = () for down_block_res_sample, down_block_additional_residual in zip( _lowerCamelCase , _lowerCamelCase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) A_ : List[str] = new_down_block_res_samples # 4. mid A_ : Union[str, Any] = self.mid_block(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: A_ : Dict = down_block_res_samples[-(self.layers_per_block + 1) :] A_ : str = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ : List[str] = up_block( _lowerCamelCase , temb=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , res_hidden_states_tuple=_lowerCamelCase , deterministic=not train , ) else: A_ : int = up_block(_lowerCamelCase , temb=_lowerCamelCase , res_hidden_states_tuple=_lowerCamelCase , deterministic=not train ) # 6. post-process A_ : int = self.conv_norm_out(_lowerCamelCase ) A_ : Optional[int] = nn.silu(_lowerCamelCase ) A_ : Tuple = self.conv_out(_lowerCamelCase ) A_ : Dict = jnp.transpose(_lowerCamelCase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_lowerCamelCase )
344
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase__ : int = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Tuple = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[Any] = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCamelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
344
1
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __snake_case ( _SCREAMING_SNAKE_CASE ,unittest.TestCase): """simple docstring""" lowercase = FlaxAutoencoderKL @property def __lowercase ( self : List[str] ) -> int: lowerCAmelCase_ : int = 4 lowerCAmelCase_ : Tuple = 3 lowerCAmelCase_ : Union[str, Any] = (32, 32) lowerCAmelCase_ : List[Any] = jax.random.PRNGKey(0 ) lowerCAmelCase_ : Union[str, Any] = jax.random.uniform(lowerCamelCase , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def __lowercase ( self : Any ) -> int: lowerCAmelCase_ : Any = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } lowerCAmelCase_ : Dict = self.dummy_input return init_dict, inputs_dict
354
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : str = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def UpperCamelCase_ ( ): '''simple docstring''' lowerCAmelCase_ : List[Any] = _ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCAmelCase_ : str = get_sagemaker_input() else: lowerCAmelCase_ : Optional[int] = get_cluster_input() return config def UpperCamelCase_ ( A__ : Optional[Any]=None ): '''simple docstring''' if subparsers is not None: lowerCAmelCase_ : List[str] = subparsers.add_parser("""config""" , description=A__ ) else: lowerCAmelCase_ : Optional[int] = argparse.ArgumentParser("""Accelerate config command""" , description=A__ ) parser.add_argument( """--config_file""" , default=A__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def UpperCamelCase_ ( A__ : Any ): '''simple docstring''' lowerCAmelCase_ : Dict = get_user_input() if args.config_file is not None: lowerCAmelCase_ : List[str] = args.config_file else: if not os.path.isdir(A__ ): os.makedirs(A__ ) lowerCAmelCase_ : List[Any] = default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(A__ ) else: config.to_yaml_file(A__ ) print(f'accelerate configuration saved at {config_file}' ) def UpperCamelCase_ ( ): '''simple docstring''' lowerCAmelCase_ : str = config_command_parser() lowerCAmelCase_ : Tuple = parser.parse_args() config_command(A__ ) if __name__ == "__main__": main()
89
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCAmelCase : Dict = logging.get_logger(__name__) if is_vision_available(): import PIL class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BICUBIC , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , _A = True , **_A , ): super().__init__(**_A ) __A : Tuple = size if size is not None else {'shortest_edge': 224} __A : Optional[Any] = get_size_dict(_A , default_to_square=_A ) __A : Optional[Any] = crop_size if crop_size is not None else {'height': 224, 'width': 224} __A : Any = get_size_dict(_A , default_to_square=_A , param_name='crop_size' ) __A : Any = do_resize __A : Dict = size __A : Optional[int] = resample __A : Union[str, Any] = do_center_crop __A : Optional[Any] = crop_size __A : int = do_rescale __A : Tuple = rescale_factor __A : Union[str, Any] = do_normalize __A : int = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __A : Any = image_std if image_std is not None else OPENAI_CLIP_STD __A : Union[str, Any] = do_convert_rgb def UpperCAmelCase_ ( self , _A , _A , _A = PILImageResampling.BICUBIC , _A = None , **_A , ): __A : List[str] = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) __A : Union[str, Any] = get_resize_output_image_size(_A , size=size['shortest_edge'] , default_to_square=_A ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): __A : Optional[int] = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): return rescale(_A , scale=_A , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A , _A = None , **_A , ): return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) 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 = None , _A = ChannelDimension.FIRST , **_A , ): __A : Dict = do_resize if do_resize is not None else self.do_resize __A : Union[str, Any] = size if size is not None else self.size __A : int = get_size_dict(_A , param_name='size' , default_to_square=_A ) __A : Dict = resample if resample is not None else self.resample __A : Any = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Any = crop_size if crop_size is not None else self.crop_size __A : Optional[int] = get_size_dict(_A , param_name='crop_size' , default_to_square=_A ) __A : Dict = do_rescale if do_rescale is not None else self.do_rescale __A : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __A : List[Any] = do_normalize if do_normalize is not None else self.do_normalize __A : Any = image_mean if image_mean is not None else self.image_mean __A : List[Any] = image_std if image_std is not None else self.image_std __A : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __A : Any = make_list_of_images(_A ) if not valid_images(_A ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __A : Union[str, Any] = [convert_to_rgb(_A ) for image in images] # All transformations expect numpy arrays. __A : Any = [to_numpy_array(_A ) for image in images] if do_resize: __A : int = [self.resize(image=_A , size=_A , resample=_A ) for image in images] if do_center_crop: __A : str = [self.center_crop(image=_A , size=_A ) for image in images] if do_rescale: __A : int = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: __A : List[str] = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] __A : Union[str, Any] = [to_channel_dimension_format(_A , _A ) for image in images] __A : List[Any] = {'pixel_values': images} return BatchFeature(data=_A , tensor_type=_A )
280
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
1
def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) lowercase__ : Any = str(bin(lowerCamelCase__ ) )[2:] # remove the leading "0b" lowercase__ : Any = str(bin(lowerCamelCase__ ) )[2:] # remove the leading "0b" lowercase__ : Any = max(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase__ ) , b_binary.zfill(lowerCamelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
121
def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : Union[str, Any] = [] lowercase__ : Tuple = [] lowercase__ : Any = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator lowercase__ : Any = len(lowerCamelCase__ ) if (len(lowerCamelCase__ ) > 7) else 7 # Print table header for output print( "Symbol".center(8 ) , "Stack".center(lowerCamelCase__ ) , "Postfix".center(lowerCamelCase__ ) , sep=" | " , ) print("-" * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(lowerCamelCase__ ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(lowerCamelCase__ ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(lowerCamelCase__ ) == 0: stack.append(lowerCamelCase__ ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(lowerCamelCase__ ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(lowerCamelCase__ ) # push x to stack print( x.center(8 ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , sep=" | " , ) # Output in tabular format while len(lowerCamelCase__ ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( " ".center(8 ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , sep=" | " , ) # Output in tabular format return "".join(lowerCamelCase__ ) # return Postfix as str def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : Optional[int] = list(infix[::-1] ) # reverse the infix equation for i in range(len(lowerCamelCase__ ) ): if infix[i] == "(": lowercase__ : Tuple = ")" # change "(" to ")" elif infix[i] == ")": lowercase__ : Optional[Any] = "(" # change ")" to "(" return (infix_2_postfix("".join(lowerCamelCase__ ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": lowerCAmelCase__ = input('''\nEnter an Infix Equation = ''') # Input an Infix equation lowerCAmelCase__ = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
121
1
"""simple docstring""" from statistics import mean import numpy as np def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> list: lowercase__ : Union[str, Any] = 0 # Number of processes finished lowercase__ : Optional[Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowercase__ : Union[str, Any] = [0] * no_of_process # List to include calculation results lowercase__ : List[Any] = [0] * no_of_process # Sort by arrival time. lowercase__ : int = [burst_time[i] for i in np.argsort(__lowerCamelCase )] lowercase__ : str = [process_name[i] for i in np.argsort(__lowerCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowercase__ : List[Any] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowercase__ : str = arrival_time[i] lowercase__ : Optional[Any] = 0 # Index showing the location of the process being performed lowercase__ : Optional[int] = 0 # Saves the current response ratio. lowercase__ : str = 0 for i in range(0 , __lowerCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowercase__ : Tuple = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowercase__ : int = temp lowercase__ : Optional[Any] = i # Calculate the turn around time lowercase__ : List[Any] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowercase__ : List[Any] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> list: lowercase__ : str = [0] * no_of_process for i in range(0 , __lowerCamelCase ): lowercase__ : str = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowerCAmelCase_ = 5 lowerCAmelCase_ = ['A', 'B', 'C', 'D', 'E'] lowerCAmelCase_ = [1, 2, 3, 4, 5] lowerCAmelCase_ = [1, 2, 3, 4, 5] lowerCAmelCase_ = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowerCAmelCase_ = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('Process name \tArrival time \tBurst time \tTurn around time \tWaiting time') for i in range(0, no_of_process): print( F'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' F'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(F'''average waiting time : {mean(waiting_time):.5f}''') print(F'''average turn around time : {mean(turn_around_time):.5f}''')
16
"""simple docstring""" import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCAmelCase_ = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize lowerCAmelCase_ = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' lowerCAmelCase_ = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' lowerCAmelCase_ = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\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.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): '''simple docstring''' def UpperCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Value('''string''' ,id='''sequence''' ), '''references''': datasets.Value('''string''' ,id='''sequence''' ), } ) ,codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'''] ,reference_urls=[ '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''', '''https://en.wikipedia.org/wiki/METEOR''', ] ,) def UpperCAmelCase ( self : str ,_snake_case : Dict ) -> Dict: """simple docstring""" import nltk nltk.download('''wordnet''' ) if NLTK_VERSION >= version.Version('''3.6.5''' ): nltk.download('''punkt''' ) if NLTK_VERSION >= version.Version('''3.6.6''' ): nltk.download('''omw-1.4''' ) def UpperCAmelCase ( self : Dict ,_snake_case : Dict ,_snake_case : List[str] ,_snake_case : Tuple=0.9 ,_snake_case : Optional[int]=3 ,_snake_case : Union[str, Any]=0.5 ) -> List[str]: """simple docstring""" if NLTK_VERSION >= version.Version('''3.6.5''' ): lowercase__ : int = [ meteor_score.single_meteor_score( word_tokenize(_snake_case ) ,word_tokenize(_snake_case ) ,alpha=_snake_case ,beta=_snake_case ,gamma=_snake_case ) for ref, pred in zip(_snake_case ,_snake_case ) ] else: lowercase__ : Tuple = [ meteor_score.single_meteor_score(_snake_case ,_snake_case ,alpha=_snake_case ,beta=_snake_case ,gamma=_snake_case ) for ref, pred in zip(_snake_case ,_snake_case ) ] return {"meteor": np.mean(_snake_case )}
16
1
'''simple docstring''' A : int = 9.8_06_65 def lowerCAmelCase__ ( lowerCamelCase : float ,lowerCamelCase : float ,lowerCamelCase : float = g ): if fluid_density <= 0: raise ValueError('Impossible fluid density' ) if volume < 0: raise ValueError('Impossible Object volume' ) if gravity <= 0: raise ValueError('Impossible Gravity' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
227
'''simple docstring''' from __future__ import annotations class __lowerCamelCase : """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple=None): _A : Any = data _A : Optional[Any] = None def __repr__( self : List[str]): _A : List[Any] = [] _A : Any = self while temp: string_rep.append(F'{temp.data}') _A : List[Any] = temp.next return "->".join(SCREAMING_SNAKE_CASE) def lowerCAmelCase__ ( lowerCamelCase : list ): if not elements_list: raise Exception('The Elements List is empty' ) _A : Union[str, Any] = Node(elements_list[0] ) for i in range(1 ,len(lowerCamelCase ) ): _A : Dict = Node(elements_list[i] ) _A : int = current.next return head def lowerCAmelCase__ ( lowerCamelCase : Node ): if head_node is not None and isinstance(lowerCamelCase ,lowerCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase__ ( ): from doctest import testmod testmod() _A : List[str] = make_linked_list([14, 52, 14, 12, 43] ) print('Linked List:' ) print(lowerCamelCase ) print('Elements in Reverse:' ) print_reverse(lowerCamelCase ) if __name__ == "__main__": main()
227
1
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = "EncodecFeatureExtractor" SCREAMING_SNAKE_CASE_ : List[str] = ("T5Tokenizer", "T5TokenizerFast") def __init__( self : Any , A : Union[str, Any] , A : Tuple ) -> int: super().__init__(A , A ) lowercase_ : int = self.feature_extractor lowercase_ : Union[str, Any] = False def A ( self : Dict , A : Optional[Any]=None , A : Optional[Any]=None , A : List[Any]=True ) -> Dict: return self.tokenizer.get_decoder_prompt_ids(task=A , language=A , no_timestamps=A ) def __call__( self : Optional[int] , *A : str , **A : Any ) -> int: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*A , **A ) lowercase_ : Any = kwargs.pop('''audio''' , A ) lowercase_ : Dict = kwargs.pop('''sampling_rate''' , A ) lowercase_ : Dict = kwargs.pop('''text''' , A ) if len(A ) > 0: lowercase_ : Optional[int] = args[0] lowercase_ : Dict = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if text is not None: lowercase_ : Tuple = self.tokenizer(A , **A ) if audio is not None: lowercase_ : List[str] = self.feature_extractor(A , *A , sampling_rate=A , **A ) if audio is None: return inputs elif text is None: return audio_inputs else: lowercase_ : Optional[Any] = audio_inputs['''input_values'''] if "padding_mask" in audio_inputs: lowercase_ : List[str] = audio_inputs['''padding_mask'''] return inputs def A ( self : str , *A : Optional[int] , **A : List[str] ) -> str: lowercase_ : List[str] = kwargs.pop('''audio''' , A ) lowercase_ : List[str] = kwargs.pop('''padding_mask''' , A ) if len(A ) > 0: lowercase_ : Union[str, Any] = args[0] lowercase_ : str = args[1:] if audio_values is not None: return self._decode_audio(A , padding_mask=A ) else: return self.tokenizer.batch_decode(*A , **A ) def A ( self : Optional[int] , *A : Tuple , **A : List[Any] ) -> Optional[Any]: return self.tokenizer.decode(*A , **A ) def A ( self : Any , A : Dict , A : Optional = None ) -> List[np.ndarray]: lowercase_ : Optional[Any] = to_numpy(A ) lowercase_ , lowercase_ , lowercase_ : str = audio_values.shape if padding_mask is None: return list(A ) lowercase_ : List[Any] = to_numpy(A ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowercase_ : int = seq_len - padding_mask.shape[-1] lowercase_ : List[str] = 1 - self.feature_extractor.padding_value lowercase_ : str = np.pad(A , ((0, 0), (0, difference)) , '''constant''' , constant_values=A ) lowercase_ : Union[str, Any] = audio_values.tolist() for i in range(A ): lowercase_ : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowercase_ : str = sliced_audio.reshape(A , -1 ) return audio_values
33
"""simple docstring""" import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE : List[str] = getLogger(__name__) def lowercase ( _snake_case : Tuple , _snake_case : str , _snake_case : str , _snake_case : int = 8 , _snake_case : int = 1_024 , _snake_case : Any="val" , _snake_case : Tuple=None , _snake_case : Any=False , _snake_case : str="summarization" , _snake_case : Dict=None , _snake_case : Optional[Any]=1 , _snake_case : Dict = None , _snake_case : List[Any]="" , **_snake_case : int , ) ->Dict: """simple docstring""" __snake_case : int = str(_snake_case ) assert local_rank is not None torch.distributed.init_process_group(backend='''nccl''' , rank=_snake_case ) __snake_case : Optional[Any] = Path(_snake_case ) __snake_case : str = save_dir.joinpath(f"""rank_{local_rank}_output.json""" ) torch.cuda.set_device(_snake_case ) __snake_case : Tuple = AutoModelForSeqaSeqLM.from_pretrained(_snake_case ).cuda() if fpaa: __snake_case : List[str] = model.half() # determine if we need to increase num_beams use_task_specific_params(_snake_case , _snake_case ) # update config with task specific params __snake_case : Dict = generate_kwargs.pop('''num_beams''' , model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: __snake_case : Optional[Any] = num_return_sequences __snake_case : Dict = AutoTokenizer.from_pretrained(_snake_case ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. if max_source_length is None: __snake_case : List[str] = tokenizer.model_max_length if prefix is None: __snake_case : List[str] = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' __snake_case : List[str] = SeqaSeqDataset( _snake_case , _snake_case , _snake_case , max_target_length=1_024 , type_path=_snake_case , n_obs=_snake_case , prefix=_snake_case , **_snake_case , ) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. __snake_case : Union[str, Any] = ds.make_sortish_sampler(_snake_case , distributed=_snake_case , add_extra_examples=_snake_case , shuffle=_snake_case ) __snake_case : List[Any] = DataLoader(_snake_case , sampler=_snake_case , batch_size=_snake_case , collate_fn=ds.collate_fn ) __snake_case : Union[str, Any] = [] for batch in tqdm(_snake_case ): __snake_case : Tuple = model.generate( input_ids=batch['''input_ids'''].to(model.device ) , attention_mask=batch['''attention_mask'''].to(model.device ) , num_return_sequences=_snake_case , num_beams=_snake_case , **_snake_case , ) __snake_case : List[Any] = tokenizer.batch_decode(_snake_case , skip_special_tokens=_snake_case , clean_up_tokenization_spaces=_snake_case ) __snake_case : List[str] = batch['''ids'''] if num_return_sequences > 1: __snake_case : Dict = chunks(_snake_case , _snake_case ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(_snake_case ): results.append({'''pred''': pred, '''id''': ids[i].item()} ) save_json(_snake_case , _snake_case ) return results, sampler.num_replicas def lowercase ( ) ->int: """simple docstring""" __snake_case : Any = argparse.ArgumentParser( epilog='''Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate''' ) parser.add_argument('''--data_dir''' , type=_snake_case , help='''like cnn_dm/test.source''' ) parser.add_argument( '''--model_name''' , type=_snake_case , help='''like facebook/bart-large-cnn,t5-base, etc.''' , default='''sshleifer/distilbart-xsum-12-3''' , ) parser.add_argument('''--save_dir''' , type=_snake_case , help='''where to save''' , default='''tmp_gen''' ) parser.add_argument('''--max_source_length''' , type=_snake_case , default=_snake_case ) parser.add_argument( '''--type_path''' , type=_snake_case , default='''test''' , help='''which subset to evaluate typically train/val/test''' ) parser.add_argument('''--task''' , type=_snake_case , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=_snake_case , default=8 , required=_snake_case , help='''batch size''' ) parser.add_argument( '''--local_rank''' , type=_snake_case , default=-1 , required=_snake_case , help='''should be passed by distributed.launch''' ) parser.add_argument( '''--n_obs''' , type=_snake_case , default=_snake_case , required=_snake_case , help='''How many observations. Defaults to all.''' ) parser.add_argument( '''--num_return_sequences''' , type=_snake_case , default=1 , required=_snake_case , help='''How many sequences to return''' ) parser.add_argument( '''--sync_timeout''' , type=_snake_case , default=600 , required=_snake_case , help='''How long should master process wait for other processes to finish.''' , ) parser.add_argument('''--src_lang''' , type=_snake_case , default=_snake_case , required=_snake_case ) parser.add_argument('''--tgt_lang''' , type=_snake_case , default=_snake_case , required=_snake_case ) parser.add_argument( '''--prefix''' , type=_snake_case , required=_snake_case , default=_snake_case , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--debug''' , action='''store_true''' ) __snake_case : str = time.time() __snake_case , __snake_case : Any = parser.parse_known_args() __snake_case : List[Any] = parse_numeric_n_bool_cl_kwargs(_snake_case ) if generate_kwargs and args.local_rank <= 0: print(f"""parsed the following generate kwargs: {generate_kwargs}""" ) __snake_case : List[Any] = Path(args.save_dir + '''_tmp''' ) Path(_snake_case ).mkdir(exist_ok=_snake_case ) # this handles locking. __snake_case : Optional[int] = list(json_save_dir.glob('''rank_*.json''' ) ) if intermediate_files: raise ValueError(f"""Found files at {json_save_dir} please move or remove them.""" ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. __snake_case : Dict = {} if args.src_lang is not None: __snake_case : Dict = args.src_lang if args.tgt_lang is not None: __snake_case : Dict = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=_snake_case ) __snake_case , __snake_case : List[Any] = eval_data_dir( args.data_dir , _snake_case , args.model_name , type_path=args.type_path , bs=args.bs , fpaa=args.fpaa , task=args.task , local_rank=args.local_rank , n_obs=args.n_obs , max_source_length=args.max_source_length , num_return_sequences=args.num_return_sequences , prefix=args.prefix , dataset_kwargs=_snake_case , **_snake_case , ) if args.local_rank <= 0: __snake_case : int = Path(args.save_dir ) save_dir.mkdir(exist_ok=_snake_case ) __snake_case : Optional[Any] = gather_results_from_each_node(_snake_case , _snake_case , args.sync_timeout ) __snake_case : str = combine_partial_results(_snake_case ) if args.num_return_sequences > 1: __snake_case : List[Any] = save_dir.joinpath('''pseudolabel_results.json''' ) print(f"""Saving aggregated results at {save_path}, intermediate in {json_save_dir}/""" ) save_json(_snake_case , _snake_case ) return __snake_case : Tuple = Path(args.data_dir ).joinpath(args.type_path + '''.target''' ) with open(_snake_case ) as f: __snake_case : Optional[Any] = [x.rstrip() for x in f.readlines()][: len(_snake_case )] # Calculate metrics, save metrics, and save _generations.txt __snake_case : List[str] = '''translation''' in args.task __snake_case : List[Any] = calculate_bleu if calc_bleu else calculate_rouge __snake_case : Dict = '''bleu''' if calc_bleu else '''rouge''' __snake_case : Dict = score_fn(_snake_case , _snake_case ) __snake_case : int = len(_snake_case ) __snake_case : Dict = time.time() - start_time __snake_case : Optional[Any] = round(runtime / metrics['''n_obs'''] , 4 ) __snake_case : List[Any] = num_replicas # TODO(@stas00): add whatever metadata to metrics __snake_case : int = save_dir.joinpath(f"""{args.type_path}_{metric_name}.json""" ) save_json(_snake_case , _snake_case , indent=_snake_case ) print(_snake_case ) write_txt_file(_snake_case , save_dir.joinpath(f"""{args.type_path}_generations.txt""" ) ) if args.debug: write_txt_file(_snake_case , save_dir.joinpath(f"""{args.type_path}.target""" ) ) else: shutil.rmtree(_snake_case ) def lowercase ( _snake_case : Union[str, Any] ) ->List: """simple docstring""" __snake_case : List[Any] = [] for partial_result in partial_results: records.extend(_snake_case ) __snake_case : List[str] = sorted(_snake_case , key=lambda _snake_case : x["id"] ) __snake_case : Tuple = [x['''pred'''] for x in records] return preds def lowercase ( _snake_case : int , _snake_case : List[str] , _snake_case : List[Any] ) ->List[Dict[str, List]]: """simple docstring""" __snake_case : List[str] = time.time() logger.info('''waiting for all nodes to finish''' ) __snake_case : List[str] = None while (time.time() - start_wait) < timeout: __snake_case : Any = list(save_dir.glob('''rank_*.json''' ) ) if len(_snake_case ) < num_replicas: continue try: # make sure all json files are fully saved __snake_case : Tuple = lmap(_snake_case , _snake_case ) return json_data except JSONDecodeError: continue else: raise TimeoutError('''Rank 0 gave up on waiting for other processes''' ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
102
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { 'facebook/deit-base-distilled-patch16-224': ( 'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class snake_case ( SCREAMING_SNAKE_CASE_ ): a_ : Optional[int] = """deit""" def __init__( self , __UpperCAmelCase=7_68 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=30_72 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=2_24 , __UpperCAmelCase=16 , __UpperCAmelCase=3 , __UpperCAmelCase=True , __UpperCAmelCase=16 , **__UpperCAmelCase , ) ->Dict: super().__init__(**__UpperCAmelCase) 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_ = encoder_stride class snake_case ( SCREAMING_SNAKE_CASE_ ): a_ : Dict = version.parse("""1.11""" ) @property def UpperCAmelCase__ ( self) ->Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def UpperCAmelCase__ ( self) ->float: return 1E-4
358
"""simple docstring""" import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class snake_case : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=50 , __UpperCAmelCase=0.02 , __UpperCAmelCase=True , __UpperCAmelCase=None , ) ->Dict: a_ = parent a_ = batch_size a_ = seq_length a_ = is_training a_ = use_input_mask 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_ = initializer_range a_ = use_labels a_ = scope def UpperCAmelCase__ ( self) ->Any: 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]) if self.use_labels: a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a_ = self.get_config() return config, input_ids, input_mask, token_labels def UpperCAmelCase__ ( self) ->Optional[Any]: return BertGenerationConfig( 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 , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self) ->List[str]: ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) = self.prepare_config_and_inputs() a_ = True a_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) a_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) ->str: a_ = BertGenerationEncoder(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase) a_ = model(__UpperCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) ->Union[str, Any]: a_ = True a_ = BertGenerationEncoder(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) ->List[str]: a_ = True a_ = True a_ = BertGenerationDecoder(config=__UpperCAmelCase).to(__UpperCAmelCase).eval() # first forward pass a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase , ) a_ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids a_ = ids_tensor((self.batch_size, 3) , config.vocab_size) a_ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and a_ = torch.cat([input_ids, next_tokens] , dim=-1) a_ = torch.cat([input_mask, next_mask] , dim=-1) a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["hidden_states"][0] a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["hidden_states"][0] # select random slice a_ = ids_tensor((1,) , output_from_past.shape[-1]).item() a_ = output_from_no_past[:, -3:, random_slice_idx].detach() a_ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-3)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , *__UpperCAmelCase , ) ->Tuple: a_ = BertGenerationDecoder(__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase__ ( self) ->str: a_ , a_ , a_ , a_ = self.prepare_config_and_inputs() a_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class snake_case ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): a_ : List[str] = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () a_ : Optional[int] = (BertGenerationDecoder,) if is_torch_available() else () a_ : List[Any] = ( {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder} if is_torch_available() else {} ) def UpperCAmelCase__ ( self) ->List[Any]: a_ = BertGenerationEncoderTester(self) a_ = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37) def UpperCAmelCase__ ( self) ->Optional[Any]: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self) ->Tuple: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Tuple: a_ , a_ , a_ , a_ = self.model_tester.prepare_config_and_inputs() a_ = "bert" self.model_tester.create_and_check_model(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->int: a_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->List[str]: a_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Optional[int]: # This regression test was failing with PyTorch < 1.3 ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() a_ = None self.model_tester.create_and_check_model_as_decoder( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) def UpperCAmelCase__ ( self) ->List[Any]: a_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__UpperCAmelCase) @slow def UpperCAmelCase__ ( self) ->str: a_ = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder") self.assertIsNotNone(__UpperCAmelCase) @require_torch class snake_case ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self) ->int: a_ = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder") a_ = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]]) with torch.no_grad(): a_ = model(__UpperCAmelCase)[0] a_ = torch.Size([1, 8, 10_24]) self.assertEqual(output.shape , __UpperCAmelCase) a_ = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4)) @require_torch class snake_case ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self) ->List[str]: a_ = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder") a_ = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]]) with torch.no_grad(): a_ = model(__UpperCAmelCase)[0] a_ = torch.Size([1, 8, 5_03_58]) self.assertEqual(output.shape , __UpperCAmelCase) a_ = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4))
303
0
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) A__ = logging.get_logger(__name__) # pylint: disable=invalid-name A__ = """ Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior.to(\"cuda\") >>> prompt = \"A red cartoon frog, 4k\" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16 ... ) >>> pipe.to(\"cuda\") >>> init_image = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/frog.png\" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save(\"red_frog.png\") ``` """ def _UpperCAmelCase ( snake_case , snake_case , snake_case=8 ): """simple docstring""" _lowerCAmelCase = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _lowerCAmelCase = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _UpperCAmelCase ( snake_case , snake_case=5_12 , snake_case=5_12 ): """simple docstring""" _lowerCAmelCase = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) _lowerCAmelCase = np.array(pil_image.convert("""RGB""" ) ) _lowerCAmelCase = arr.astype(np.floataa ) / 127.5 - 1 _lowerCAmelCase = np.transpose(snake_case , [2, 0, 1] ) _lowerCAmelCase = torch.from_numpy(snake_case ).unsqueeze(0 ) return image class __lowerCAmelCase ( lowerCamelCase__ ): def __init__( self , _snake_case , _snake_case , _snake_case , ): """simple docstring""" super().__init__() self.register_modules( unet=_snake_case , scheduler=_snake_case , movq=_snake_case , ) _lowerCAmelCase = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case ( self , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = min(int(num_inference_steps * strength ) , _snake_case ) _lowerCAmelCase = max(num_inference_steps - init_timestep , 0 ) _lowerCAmelCase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case=None ): """simple docstring""" if not isinstance(_snake_case , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_snake_case )}' ) _lowerCAmelCase = image.to(device=_snake_case , dtype=_snake_case ) _lowerCAmelCase = batch_size * num_images_per_prompt if image.shape[1] == 4: _lowerCAmelCase = image else: if isinstance(_snake_case , _snake_case ) and len(_snake_case ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(_snake_case )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) elif isinstance(_snake_case , _snake_case ): _lowerCAmelCase = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_snake_case ) ] _lowerCAmelCase = torch.cat(_snake_case , dim=0 ) else: _lowerCAmelCase = self.movq.encode(_snake_case ).latent_dist.sample(_snake_case ) _lowerCAmelCase = self.movq.config.scaling_factor * init_latents _lowerCAmelCase = torch.cat([init_latents] , dim=0 ) _lowerCAmelCase = init_latents.shape _lowerCAmelCase = randn_tensor(_snake_case , generator=_snake_case , device=_snake_case , dtype=_snake_case ) # get latents _lowerCAmelCase = self.scheduler.add_noise(_snake_case , _snake_case , _snake_case ) _lowerCAmelCase = init_latents return latents def snake_case ( self , _snake_case=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _lowerCAmelCase = torch.device(F'cuda:{gpu_id}' ) _lowerCAmelCase = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_snake_case , _snake_case ) def snake_case ( self , _snake_case=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _lowerCAmelCase = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=_snake_case ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _lowerCAmelCase = None for cpu_offloaded_model in [self.unet, self.movq]: _lowerCAmelCase , _lowerCAmelCase = cpu_offload_with_hook(_snake_case , _snake_case , prev_module_hook=_snake_case ) # We'll offload the last model manually. _lowerCAmelCase = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case ( self ): """simple docstring""" if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(_snake_case , """_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() @replace_example_docstring(_snake_case ) def __call__( self , _snake_case , _snake_case , _snake_case , _snake_case = 512 , _snake_case = 512 , _snake_case = 100 , _snake_case = 4.0 , _snake_case = 0.3 , _snake_case = 1 , _snake_case = None , _snake_case = "pil" , _snake_case = True , ): """simple docstring""" _lowerCAmelCase = self._execution_device _lowerCAmelCase = guidance_scale > 1.0 if isinstance(_snake_case , _snake_case ): _lowerCAmelCase = torch.cat(_snake_case , dim=0 ) _lowerCAmelCase = image_embeds.shape[0] if isinstance(_snake_case , _snake_case ): _lowerCAmelCase = torch.cat(_snake_case , dim=0 ) if do_classifier_free_guidance: _lowerCAmelCase = image_embeds.repeat_interleave(_snake_case , dim=0 ) _lowerCAmelCase = negative_image_embeds.repeat_interleave(_snake_case , dim=0 ) _lowerCAmelCase = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_snake_case ) if not isinstance(_snake_case , _snake_case ): _lowerCAmelCase = [image] if not all(isinstance(_snake_case , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'Input is in incorrect format: {[type(_snake_case ) for i in image]}. Currently, we only support PIL image and pytorch tensor' ) _lowerCAmelCase = torch.cat([prepare_image(_snake_case , _snake_case , _snake_case ) for i in image] , dim=0 ) _lowerCAmelCase = image.to(dtype=image_embeds.dtype , device=_snake_case ) _lowerCAmelCase = self.movq.encode(_snake_case )["""latents"""] _lowerCAmelCase = latents.repeat_interleave(_snake_case , dim=0 ) self.scheduler.set_timesteps(_snake_case , device=_snake_case ) _lowerCAmelCase , _lowerCAmelCase = self.get_timesteps(_snake_case , _snake_case , _snake_case ) _lowerCAmelCase = timesteps[:1].repeat(batch_size * num_images_per_prompt ) _lowerCAmelCase , _lowerCAmelCase = downscale_height_and_width(_snake_case , _snake_case , self.movq_scale_factor ) _lowerCAmelCase = self.prepare_latents( _snake_case , _snake_case , _snake_case , _snake_case , image_embeds.dtype , _snake_case , _snake_case ) for i, t in enumerate(self.progress_bar(_snake_case ) ): # expand the latents if we are doing classifier free guidance _lowerCAmelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _lowerCAmelCase = {"""image_embeds""": image_embeds} _lowerCAmelCase = self.unet( sample=_snake_case , timestep=_snake_case , encoder_hidden_states=_snake_case , added_cond_kwargs=_snake_case , return_dict=_snake_case , )[0] if do_classifier_free_guidance: _lowerCAmelCase , _lowerCAmelCase = noise_pred.split(latents.shape[1] , dim=1 ) _lowerCAmelCase , _lowerCAmelCase = noise_pred.chunk(2 ) _lowerCAmelCase , _lowerCAmelCase = variance_pred.chunk(2 ) _lowerCAmelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _lowerCAmelCase = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _lowerCAmelCase , _lowerCAmelCase = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _lowerCAmelCase = self.scheduler.step( _snake_case , _snake_case , _snake_case , generator=_snake_case , )[0] # post-processing _lowerCAmelCase = self.movq.decode(_snake_case , force_not_quantize=_snake_case )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _lowerCAmelCase = image * 0.5 + 0.5 _lowerCAmelCase = image.clamp(0 , 1 ) _lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _lowerCAmelCase = self.numpy_to_pil(_snake_case ) if not return_dict: return (image,) return ImagePipelineOutput(images=_snake_case )
82
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } __UpperCamelCase = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]: for attribute in key.split('.' ): snake_case_ = getattr(UpperCAmelCase , UpperCAmelCase ) if weight_type is not None: snake_case_ = getattr(UpperCAmelCase , UpperCAmelCase ).shape else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "running_mean": snake_case_ = value elif weight_type == "running_var": snake_case_ = value elif weight_type == "num_batches_tracked": snake_case_ = value elif weight_type == "inv_freq": snake_case_ = value else: snake_case_ = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> int: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , hf_model.config.feat_extract_norm == 'group' , ) snake_case_ = True else: for key, mapped_key in MAPPING.items(): snake_case_ = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(UpperCAmelCase )[0].split('.' )[-2] snake_case_ = mapped_key.replace('*' , UpperCAmelCase ) if "pos_bias_u" in name: snake_case_ = None elif "pos_bias_v" in name: snake_case_ = None elif "weight_g" in name: snake_case_ = 'weight_g' elif "weight_v" in name: snake_case_ = 'weight_v' elif "bias" in name: snake_case_ = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = 'weight' elif "running_mean" in name: snake_case_ = 'running_mean' elif "inv_freq" in name: snake_case_ = 'inv_freq' elif "running_var" in name: snake_case_ = 'running_var' elif "num_batches_tracked" in name: snake_case_ = 'num_batches_tracked' else: snake_case_ = None set_recursively(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) continue if not is_used: unused_weights.append(UpperCAmelCase ) logger.warning(f'Unused weights: {unused_weights}' ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: snake_case_ = full_name.split('conv_layers.' )[-1] snake_case_ = name.split('.' ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(UpperCAmelCase ) @torch.no_grad() def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=True ) -> str: if config_path is not None: snake_case_ = WavaVecaConformerConfig.from_pretrained(UpperCAmelCase , hidden_act='swish' ) else: snake_case_ = WavaVecaConformerConfig() if "rope" in checkpoint_path: snake_case_ = 'rotary' if is_finetuned: if dict_path: snake_case_ = Dictionary.load(UpperCAmelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(UpperCAmelCase , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase ) ) return os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(UpperCAmelCase , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase , UpperCAmelCase ) snake_case_ = WavaVecaCTCTokenizer( UpperCAmelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase , ) snake_case_ = True if config.feat_extract_norm == 'layer' else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCAmelCase , return_attention_mask=UpperCAmelCase , ) snake_case_ = WavaVecaProcessor(feature_extractor=UpperCAmelCase , tokenizer=UpperCAmelCase ) processor.save_pretrained(UpperCAmelCase ) snake_case_ = WavaVecaConformerForCTC(UpperCAmelCase ) else: snake_case_ = WavaVecaConformerForPreTraining(UpperCAmelCase ) if is_finetuned: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: snake_case_ = argparse.Namespace(task='audio_pretraining' ) snake_case_ = fairseq.tasks.setup_task(UpperCAmelCase ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase ) snake_case_ = model[0].eval() recursively_load_weights(UpperCAmelCase , UpperCAmelCase , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __UpperCamelCase = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
69
0
import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=1 ): '''simple docstring''' if n_shave_prefix_segments >= 0: return ".".join(path.split('''.''' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('''.''' )[:n_shave_prefix_segments] ) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=0 ): '''simple docstring''' lowercase = [] for old_item in old_list: lowercase = old_item.replace('''in_layers.0''' , '''norm1''' ) lowercase = new_item.replace('''in_layers.2''' , '''conv1''' ) lowercase = new_item.replace('''out_layers.0''' , '''norm2''' ) lowercase = new_item.replace('''out_layers.3''' , '''conv2''' ) lowercase = new_item.replace('''emb_layers.1''' , '''time_emb_proj''' ) lowercase = new_item.replace('''skip_connection''' , '''conv_shortcut''' ) lowercase = shave_segments(lowerCAmelCase__ , n_shave_prefix_segments=lowerCAmelCase__ ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=0 ): '''simple docstring''' lowercase = [] for old_item in old_list: lowercase = old_item lowercase = new_item.replace('''norm.weight''' , '''group_norm.weight''' ) lowercase = new_item.replace('''norm.bias''' , '''group_norm.bias''' ) lowercase = new_item.replace('''proj_out.weight''' , '''proj_attn.weight''' ) lowercase = new_item.replace('''proj_out.bias''' , '''proj_attn.bias''' ) lowercase = shave_segments(lowerCAmelCase__ , n_shave_prefix_segments=lowerCAmelCase__ ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None ): '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowercase = old_checkpoint[path] lowercase = old_tensor.shape[0] // 3 lowercase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowercase = old_tensor.shape[0] // config['''num_head_channels'''] // 3 lowercase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowercase , lowercase , lowercase = old_tensor.split(channels // num_heads , dim=1 ) lowercase = query.reshape(lowerCAmelCase__ ) lowercase = key.reshape(lowerCAmelCase__ ) lowercase = value.reshape(lowerCAmelCase__ ) for path in paths: lowercase = path['''new'''] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowercase = new_path.replace('''middle_block.0''' , '''mid_block.resnets.0''' ) lowercase = new_path.replace('''middle_block.1''' , '''mid_block.attentions.0''' ) lowercase = new_path.replace('''middle_block.2''' , '''mid_block.resnets.1''' ) if additional_replacements is not None: for replacement in additional_replacements: lowercase = new_path.replace(replacement['''old'''] , replacement['''new'''] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowercase = old_checkpoint[path['''old''']][:, :, 0] else: lowercase = old_checkpoint[path['''old''']] def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = {} lowercase = checkpoint['''time_embed.0.weight'''] lowercase = checkpoint['''time_embed.0.bias'''] lowercase = checkpoint['''time_embed.2.weight'''] lowercase = checkpoint['''time_embed.2.bias'''] lowercase = checkpoint['''input_blocks.0.0.weight'''] lowercase = checkpoint['''input_blocks.0.0.bias'''] lowercase = checkpoint['''out.0.weight'''] lowercase = checkpoint['''out.0.bias'''] lowercase = checkpoint['''out.2.weight'''] lowercase = checkpoint['''out.2.bias'''] # Retrieves the keys for the input blocks only lowercase = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''input_blocks''' in layer} ) lowercase = { layer_id: [key for key in checkpoint if f'input_blocks.{layer_id}' in key] for layer_id in range(lowerCAmelCase__ ) } # Retrieves the keys for the middle blocks only lowercase = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''middle_block''' in layer} ) lowercase = { layer_id: [key for key in checkpoint if f'middle_block.{layer_id}' in key] for layer_id in range(lowerCAmelCase__ ) } # Retrieves the keys for the output blocks only lowercase = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''output_blocks''' in layer} ) lowercase = { layer_id: [key for key in checkpoint if f'output_blocks.{layer_id}' in key] for layer_id in range(lowerCAmelCase__ ) } for i in range(1 , lowerCAmelCase__ ): lowercase = (i - 1) // (config['''num_res_blocks'''] + 1) lowercase = (i - 1) % (config['''num_res_blocks'''] + 1) lowercase = [key for key in input_blocks[i] if f'input_blocks.{i}.0' in key] lowercase = [key for key in input_blocks[i] if f'input_blocks.{i}.1' in key] if f'input_blocks.{i}.0.op.weight' in checkpoint: lowercase = checkpoint[ f'input_blocks.{i}.0.op.weight' ] lowercase = checkpoint[ f'input_blocks.{i}.0.op.bias' ] continue lowercase = renew_resnet_paths(lowerCAmelCase__ ) lowercase = {'''old''': f'input_blocks.{i}.0', '''new''': f'down_blocks.{block_id}.resnets.{layer_in_block_id}'} lowercase = {'''old''': '''resnets.2.op''', '''new''': '''downsamplers.0.op'''} assign_to_checkpoint( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase__ ) if len(lowerCAmelCase__ ): lowercase = renew_attention_paths(lowerCAmelCase__ ) lowercase = { '''old''': f'input_blocks.{i}.1', '''new''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}', } lowercase = { f'input_blocks.{i}.1.qkv.bias': { '''key''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', '''query''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', '''value''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'input_blocks.{i}.1.qkv.weight': { '''key''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', '''query''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', '''value''': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase__ , config=lowerCAmelCase__ , ) lowercase = middle_blocks[0] lowercase = middle_blocks[1] lowercase = middle_blocks[2] lowercase = renew_resnet_paths(lowerCAmelCase__ ) assign_to_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , config=lowerCAmelCase__ ) lowercase = renew_resnet_paths(lowerCAmelCase__ ) assign_to_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , config=lowerCAmelCase__ ) lowercase = renew_attention_paths(lowerCAmelCase__ ) lowercase = { '''middle_block.1.qkv.bias''': { '''key''': '''mid_block.attentions.0.key.bias''', '''query''': '''mid_block.attentions.0.query.bias''', '''value''': '''mid_block.attentions.0.value.bias''', }, '''middle_block.1.qkv.weight''': { '''key''': '''mid_block.attentions.0.key.weight''', '''query''': '''mid_block.attentions.0.query.weight''', '''value''': '''mid_block.attentions.0.value.weight''', }, } assign_to_checkpoint( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , attention_paths_to_split=lowerCAmelCase__ , config=lowerCAmelCase__ ) for i in range(lowerCAmelCase__ ): lowercase = i // (config['''num_res_blocks'''] + 1) lowercase = i % (config['''num_res_blocks'''] + 1) lowercase = [shave_segments(lowerCAmelCase__ , 2 ) for name in output_blocks[i]] lowercase = {} for layer in output_block_layers: lowercase , lowercase = layer.split('''.''' )[0], shave_segments(lowerCAmelCase__ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase__ ) else: lowercase = [layer_name] if len(lowerCAmelCase__ ) > 1: lowercase = [key for key in output_blocks[i] if f'output_blocks.{i}.0' in key] lowercase = [key for key in output_blocks[i] if f'output_blocks.{i}.1' in key] lowercase = renew_resnet_paths(lowerCAmelCase__ ) lowercase = renew_resnet_paths(lowerCAmelCase__ ) lowercase = {'''old''': f'output_blocks.{i}.0', '''new''': f'up_blocks.{block_id}.resnets.{layer_in_block_id}'} assign_to_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , additional_replacements=[meta_path] , config=lowerCAmelCase__ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowercase = list(output_block_list.values() ).index(['''conv.weight''', '''conv.bias'''] ) lowercase = checkpoint[ f'output_blocks.{i}.{index}.conv.weight' ] lowercase = checkpoint[ f'output_blocks.{i}.{index}.conv.bias' ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase__ ) == 2: lowercase = [] if len(lowerCAmelCase__ ): lowercase = renew_attention_paths(lowerCAmelCase__ ) lowercase = { '''old''': f'output_blocks.{i}.1', '''new''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}', } lowercase = { f'output_blocks.{i}.1.qkv.bias': { '''key''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', '''query''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', '''value''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'output_blocks.{i}.1.qkv.weight': { '''key''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', '''query''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', '''value''': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('''qkv''' in key for key in attentions ) else None , config=lowerCAmelCase__ , ) else: lowercase = renew_resnet_paths(lowerCAmelCase__ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowercase = '''.'''.join(['''output_blocks''', str(lowerCAmelCase__ ), path['''old''']] ) lowercase = '''.'''.join(['''up_blocks''', str(lowerCAmelCase__ ), '''resnets''', str(lowerCAmelCase__ ), path['''new''']] ) lowercase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": lowercase__ :str = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the architecture.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") lowercase__ :Optional[Any] = parser.parse_args() lowercase__ :str = torch.load(args.checkpoint_path) with open(args.config_file) as f: lowercase__ :Optional[Any] = json.loads(f.read()) lowercase__ :str = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] lowercase__ :List[Any] = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: lowercase__ :Tuple = DDPMScheduler.from_config("/".join(args.checkpoint_path.split("/")[:-1])) lowercase__ :List[Any] = VQModel.from_pretrained("/".join(args.checkpoint_path.split("/")[:-1])) lowercase__ :Any = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
97
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class lowercase ( unittest.TestCase ): @slow def A__ ( self): lowercase = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''') lowercase = { '''input_ids''': tf.convert_to_tensor([[0, 2_6_4_6, 1_0_2_6_9, 8_3, 9_9_9_4_2, 2]] ,dtype=tf.intaa), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] ,dtype=tf.intaa), } lowercase = model(A__)['''last_hidden_state'''] lowercase = tf.TensorShape((1, 6, 7_6_8)) self.assertEqual(output.shape ,A__) # compare the actual values for a slice. lowercase = tf.convert_to_tensor( [ [ [0.0681762, 0.10894451, 0.06772504], [-0.06423668, 0.02366615, 0.04329344], [-0.06057295, 0.09974135, -0.00070584], ] ] ,dtype=tf.floataa ,) self.assertTrue(np.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1E-4))
97
1
'''simple docstring''' def A_ ( ): return [list(range(1000 - i , -1000 - i , -1 ) ) for i in range(1000 )] A_ = generate_large_matrix() A_ = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def A_ ( snake_case ): assert all(row == sorted(snake_case , reverse=snake_case ) for row in grid ) assert all(list(snake_case ) == sorted(snake_case , reverse=snake_case ) for col in zip(*snake_case ) ) def A_ ( snake_case ): SCREAMING_SNAKE_CASE:int = 0 SCREAMING_SNAKE_CASE:List[Any] = len(snake_case ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: SCREAMING_SNAKE_CASE:Union[str, Any] = (left + right) // 2 SCREAMING_SNAKE_CASE:Dict = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: SCREAMING_SNAKE_CASE:Tuple = mid + 1 else: SCREAMING_SNAKE_CASE:Optional[int] = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(snake_case ) def A_ ( snake_case ): SCREAMING_SNAKE_CASE:Union[str, Any] = 0 SCREAMING_SNAKE_CASE:List[str] = len(grid[0] ) for i in range(len(snake_case ) ): SCREAMING_SNAKE_CASE:Dict = find_negative_index(grid[i][:bound] ) total += bound return (len(snake_case ) * len(grid[0] )) - total def A_ ( snake_case ): return len([number for row in grid for number in row if number < 0] ) def A_ ( snake_case ): SCREAMING_SNAKE_CASE:str = 0 for row in grid: for i, number in enumerate(snake_case ): if number < 0: total += len(snake_case ) - i break return total def A_ ( ): from timeit import timeit print("Running benchmarks" ) SCREAMING_SNAKE_CASE:Dict = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): SCREAMING_SNAKE_CASE:List[str] = timeit(F'''{func}(grid=grid)''' , setup=snake_case , number=500 ) print(F'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
139
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class _snake_case ( _a ): _A : Optional[int] = '''t5''' _A : Union[str, Any] = ['''past_key_values'''] _A : Dict = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]=32_128 ,SCREAMING_SNAKE_CASE__ : List[str]=512 ,SCREAMING_SNAKE_CASE__ : Any=64 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=2_048 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=6 ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,SCREAMING_SNAKE_CASE__ : Dict=8 ,SCREAMING_SNAKE_CASE__ : Optional[int]=32 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=128 ,SCREAMING_SNAKE_CASE__ : List[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Tuple=1e-6 ,SCREAMING_SNAKE_CASE__ : str=1.0 ,SCREAMING_SNAKE_CASE__ : int="relu" ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : Dict=0 ,SCREAMING_SNAKE_CASE__ : Tuple=1 ,**SCREAMING_SNAKE_CASE__ : Tuple ,): SCREAMING_SNAKE_CASE:int = vocab_size SCREAMING_SNAKE_CASE:Any = d_model SCREAMING_SNAKE_CASE:Union[str, Any] = d_kv SCREAMING_SNAKE_CASE:Optional[int] = d_ff SCREAMING_SNAKE_CASE:Tuple = num_layers SCREAMING_SNAKE_CASE:str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE:Union[str, Any] = num_heads SCREAMING_SNAKE_CASE:int = relative_attention_num_buckets SCREAMING_SNAKE_CASE:Tuple = relative_attention_max_distance SCREAMING_SNAKE_CASE:Dict = dropout_rate SCREAMING_SNAKE_CASE:List[Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE:List[str] = initializer_factor SCREAMING_SNAKE_CASE:Tuple = feed_forward_proj SCREAMING_SNAKE_CASE:str = use_cache SCREAMING_SNAKE_CASE:Optional[Any] = self.feed_forward_proj.split("-" ) SCREAMING_SNAKE_CASE:Any = act_info[-1] SCREAMING_SNAKE_CASE:Tuple = act_info[0] == "gated" if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE:int = "gelu_new" super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ ,eos_token_id=SCREAMING_SNAKE_CASE__ ,is_encoder_decoder=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) class _snake_case ( _a ): @property def __UpperCamelCase ( self : Tuple ): SCREAMING_SNAKE_CASE:int = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: SCREAMING_SNAKE_CASE:Optional[int] = "past_encoder_sequence + sequence" SCREAMING_SNAKE_CASE:str = {0: "batch"} SCREAMING_SNAKE_CASE:List[Any] = {0: "batch", 1: "past_decoder_sequence + sequence"} else: SCREAMING_SNAKE_CASE:Tuple = {0: "batch", 1: "decoder_sequence"} SCREAMING_SNAKE_CASE:List[Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ ,direction="inputs" ) return common_inputs @property def __UpperCamelCase ( self : Optional[int] ): return 13
139
1
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: assert isinstance(lowercase , lowercase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False _a = range(3 , int(math.sqrt(lowercase ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _lowerCamelCase ( lowercase : Any , lowercase : str=1 , **lowercase : int ) -> Dict: _a = factor * value _a = value while not is_prime(lowercase ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase ) return value
346
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
1
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Union[str, Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) __UpperCamelCase =TextIteratorStreamer(A_ ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text self.assertEqual(A_ , A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =greedy_ids[:, input_ids.shape[1] :] __UpperCamelCase =tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_prompt=A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Any: # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them __UpperCamelCase =AutoTokenizer.from_pretrained('distilgpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('distilgpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =torch.ones((1, 5) , device=A_ ).long() * model.config.bos_token_id with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_special_tokens=A_ ) model.generate(A_ , max_new_tokens=1 , do_sample=A_ , streamer=A_ ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token __UpperCamelCase =cs.out[:-1] # Remove the final "\n" __UpperCamelCase =tokenizer(A_ , return_tensors='pt' ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =TextIteratorStreamer(A_ , timeout=0.001 ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(A_ ): __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text
62
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [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: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
0
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a_ : Dict = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) a_ : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } a_ : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } a_ : Tuple = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : int = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) a_ : int = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : str = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) a_ : Optional[Any] = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : List[str] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." a_ : Tuple = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." a_ : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" a_ : Dict = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." a_ : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" a_ : Tuple = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." a_ : Tuple = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" a_ : List[str] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." a_ : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." a_ : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" a_ : int = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." a_ : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Tuple = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." a_ : Any = "" a_ : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." a_ : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : List[str] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :List[str] ) -> List[Any]: '''simple docstring''' assert ReadMe.from_string(lowerCAmelCase__ , lowerCAmelCase__ ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _A (lowerCAmelCase__ :List[str] , lowerCAmelCase__ :List[Any] ) -> List[Any]: '''simple docstring''' with pytest.raises(lowerCAmelCase__ , match=re.escape(expected_error.format(path='root' ) ) ): _a = ReadMe.from_string(lowerCAmelCase__ , lowerCAmelCase__ ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :List[str] , lowerCAmelCase__ :str ) -> str: '''simple docstring''' with pytest.raises(lowerCAmelCase__ , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :Optional[Any] ) -> int: '''simple docstring''' ReadMe.from_string(lowerCAmelCase__ , lowerCAmelCase__ , suppress_parsing_errors=lowerCAmelCase__ ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :Optional[Any] ) -> Optional[int]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(lowerCAmelCase__ ) / 'README.md' with open(lowerCAmelCase__ , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase__ ) _a = ReadMe.from_readme(lowerCAmelCase__ , lowerCAmelCase__ ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :List[str] ) -> Optional[int]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(lowerCAmelCase__ ) / 'README.md' with open(lowerCAmelCase__ , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase__ ) _a = expected_error.format(path=lowerCAmelCase__ ) with pytest.raises(lowerCAmelCase__ , match=re.escape(lowerCAmelCase__ ) ): _a = ReadMe.from_readme(lowerCAmelCase__ , lowerCAmelCase__ ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Optional[int] ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(lowerCAmelCase__ ) / 'README.md' with open(lowerCAmelCase__ , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase__ ) _a = expected_error.format(path=lowerCAmelCase__ ) with pytest.raises(lowerCAmelCase__ , match=re.escape(lowerCAmelCase__ ) ): ReadMe.from_readme(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(lowerCAmelCase__ ) / 'README.md' with open(lowerCAmelCase__ , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase__ ) ReadMe.from_readme(lowerCAmelCase__ , lowerCAmelCase__ , suppress_parsing_errors=lowerCAmelCase__ )
104
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable a_ : int = { "configuration_gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"], "tokenization_gpt_neox_japanese": ["GPTNeoXJapaneseTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ "GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXJapaneseForCausalLM", "GPTNeoXJapaneseLayer", "GPTNeoXJapaneseModel", "GPTNeoXJapanesePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys a_ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
104
1
from __future__ import annotations import bisect def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0 , _lowerCamelCase = -1 ): '''simple docstring''' if hi < 0: _lowerCAmelCase : int = len(_lowerCamelCase ) while lo < hi: _lowerCAmelCase : Optional[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: _lowerCAmelCase : Union[str, Any] = mid + 1 else: _lowerCAmelCase : str = mid return lo def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0 , _lowerCamelCase = -1 ): '''simple docstring''' if hi < 0: _lowerCAmelCase : str = len(_lowerCamelCase ) while lo < hi: _lowerCAmelCase : Tuple = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: _lowerCAmelCase : Dict = mid + 1 else: _lowerCAmelCase : str = mid return lo def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0 , _lowerCamelCase = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase ) def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0 , _lowerCamelCase = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : int = 0 _lowerCAmelCase : Union[str, Any] = len(_lowerCamelCase ) - 1 while left <= right: _lowerCAmelCase : int = left + (right - left) // 2 _lowerCAmelCase : int = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: _lowerCAmelCase : str = midpoint - 1 else: _lowerCAmelCase : Any = midpoint + 1 return None def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Tuple = bisect.bisect_left(_lowerCamelCase , _lowerCamelCase ) if index != len(_lowerCamelCase ) and sorted_collection[index] == item: return index return None def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' if right < left: return None _lowerCAmelCase : Optional[int] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(_lowerCamelCase , _lowerCamelCase , midpoint + 1 , _lowerCamelCase ) if __name__ == "__main__": _snake_case = input("Enter numbers separated by comma:\n").strip() _snake_case = sorted(int(item) for item in user_input.split(",")) _snake_case = int(input("Enter a single number to be found in the list:\n")) _snake_case = binary_search(collection, target) if result is None: print(f'''{target} was not found in {collection}.''') else: print(f'''{target} was found at position {result} in {collection}.''')
36
def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : int ): return [sentence[i : i + ngram_size] for i in range(len(lowerCAmelCase_ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
284
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCAmelCase = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
1
"""simple docstring""" from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def _snake_case ( lowercase__ : str = "laptop" ) -> DataFrame: '''simple docstring''' lowerCAmelCase_ :Dict = f"""https://www.amazon.in/laptop/s?k={product}""" lowerCAmelCase_ :List[str] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } lowerCAmelCase_ :List[Any] = BeautifulSoup(requests.get(lowercase__ , headers=lowercase__ ).text ) # Initialize a Pandas dataframe with the column titles lowerCAmelCase_ :Union[str, Any] = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: lowerCAmelCase_ :str = item.ha.text lowerCAmelCase_ :Dict = """https://www.amazon.in/""" + item.ha.a["""href"""] lowerCAmelCase_ :int = item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: lowerCAmelCase_ :Dict = item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: lowerCAmelCase_ :int = """Not available""" try: lowerCAmelCase_ :str = ( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: lowerCAmelCase_ :Optional[Any] = """""" try: lowerCAmelCase_ :str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 1_0_0 ) except ValueError: lowerCAmelCase_ :Union[str, Any] = float("""nan""" ) except AttributeError: pass lowerCAmelCase_ :Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] lowerCAmelCase_ :List[Any] = """ """ lowerCAmelCase_ :Tuple = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": __UpperCAmelCase = 'headphones' get_amazon_product_data(product).to_csv(F"""Amazon Product Data for {product}.csv""")
1
1
import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 A__ : List[str] = 0b10_11_00_11_11_10_11_00_10_01_00_00_01_11_10_11_10_11_00_01_10_01_11_10 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 A__ : List[str] = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class __snake_case : def __init__( self : List[Any]): lowerCAmelCase_ : Tuple = WATERMARK_BITS lowerCAmelCase_ : int = WatermarkEncoder() self.encoder.set_watermark('''bits''' , self.watermark) def UpperCAmelCase__ ( self : Optional[Any] , A_ : torch.FloatTensor): # can't encode images that are smaller than 256 if images.shape[-1] < 2_5_6: return images lowerCAmelCase_ : Optional[Any] = (2_5_5 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1).float().numpy() lowerCAmelCase_ : Any = [self.encoder.encode(A_ , '''dwtDct''') for image in images] lowerCAmelCase_ : Optional[Any] = torch.from_numpy(np.array(A_)).permute(0 , 3 , 1 , 2) lowerCAmelCase_ : Optional[Any] = torch.clamp(2 * (images / 2_5_5 - 0.5) , min=-1.0 , max=1.0) return images
103
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A__ : List[str] = logging.get_logger(__name__) class __snake_case ( UpperCamelCase_ ,UpperCamelCase_ ): _a = '''maskformer-swin''' _a = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Union[str, Any] , A_ : Dict=2_2_4 , A_ : Optional[Any]=4 , A_ : List[str]=3 , A_ : str=9_6 , A_ : Optional[Any]=[2, 2, 6, 2] , A_ : Tuple=[3, 6, 1_2, 2_4] , A_ : List[Any]=7 , A_ : List[Any]=4.0 , A_ : List[str]=True , A_ : Dict=0.0 , A_ : int=0.0 , A_ : str=0.1 , A_ : Optional[int]="gelu" , A_ : List[Any]=False , A_ : int=0.02 , A_ : int=1e-5 , A_ : Optional[int]=None , A_ : List[str]=None , **A_ : List[Any] , ): super().__init__(**A_) lowerCAmelCase_ : Dict = image_size lowerCAmelCase_ : Optional[Any] = patch_size lowerCAmelCase_ : Tuple = num_channels lowerCAmelCase_ : Any = embed_dim lowerCAmelCase_ : List[str] = depths lowerCAmelCase_ : Union[str, Any] = len(A_) lowerCAmelCase_ : List[str] = num_heads lowerCAmelCase_ : Dict = window_size lowerCAmelCase_ : Optional[int] = mlp_ratio lowerCAmelCase_ : Dict = qkv_bias lowerCAmelCase_ : str = hidden_dropout_prob lowerCAmelCase_ : List[str] = attention_probs_dropout_prob lowerCAmelCase_ : Optional[int] = drop_path_rate lowerCAmelCase_ : Any = hidden_act lowerCAmelCase_ : str = use_absolute_embeddings lowerCAmelCase_ : List[str] = layer_norm_eps lowerCAmelCase_ : int = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCAmelCase_ : str = int(embed_dim * 2 ** (len(A_) - 1)) lowerCAmelCase_ : Optional[Any] = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(A_) + 1)] lowerCAmelCase_ , lowerCAmelCase_ : int = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names)
103
1
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Optional[int]: """simple docstring""" UpperCamelCase :List[Any] = BertConfig.from_json_file(snake_case_ ) print(f"""Building PyTorch model from configuration: {config}""" ) UpperCamelCase :Dict = BertForPreTraining(snake_case_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(snake_case_ , snake_case_ , snake_case_ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , snake_case_ ) if __name__ == "__main__": UpperCAmelCase_ : str = 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( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
369
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Any=7 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Optional[Any]=30 , __lowerCamelCase : Union[str, Any]=400 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Tuple=None , __lowerCamelCase : int=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : int=[0.5, 0.5, 0.5] , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : str=1 / 255 , __lowerCamelCase : str=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p UpperCamelCase :List[Any] = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1_333} UpperCamelCase :Tuple = parent UpperCamelCase :int = batch_size UpperCamelCase :str = num_channels UpperCamelCase :Dict = min_resolution UpperCamelCase :Any = max_resolution UpperCamelCase :int = do_resize UpperCamelCase :str = size UpperCamelCase :Dict = do_normalize UpperCamelCase :Tuple = image_mean UpperCamelCase :Optional[int] = image_std UpperCamelCase :Tuple = do_rescale UpperCamelCase :Optional[Any] = rescale_factor UpperCamelCase :List[Any] = do_pad def _A ( self : List[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _A ( self : Dict , __lowerCamelCase : Any , __lowerCamelCase : Optional[int]=False ): if not batched: UpperCamelCase :Optional[Any] = image_inputs[0] if isinstance(__lowerCamelCase , Image.Image ): UpperCamelCase , UpperCamelCase :Union[str, Any] = image.size else: UpperCamelCase , UpperCamelCase :Optional[int] = image.shape[1], image.shape[2] if w < h: UpperCamelCase :int = int(self.size["""shortest_edge"""] * h / w ) UpperCamelCase :Tuple = self.size["""shortest_edge"""] elif w > h: UpperCamelCase :List[Any] = self.size["""shortest_edge"""] UpperCamelCase :str = int(self.size["""shortest_edge"""] * w / h ) else: UpperCamelCase :List[Any] = self.size["""shortest_edge"""] UpperCamelCase :str = self.size["""shortest_edge"""] else: UpperCamelCase :List[Any] = [] for image in image_inputs: UpperCamelCase , UpperCamelCase :int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase :int = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[0] )[0] UpperCamelCase :Tuple = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[int] = DeformableDetrImageProcessor if is_vision_available() else None def _A ( self : Optional[Any] ): UpperCamelCase :str = DeformableDetrImageProcessingTester(self ) @property def _A ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : Dict ): UpperCamelCase :int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_rescale""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_pad""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : str ): UpperCamelCase :Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1_333} ) self.assertEqual(image_processor.do_pad , __lowerCamelCase ) UpperCamelCase :int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__lowerCamelCase ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , __lowerCamelCase ) def _A ( self : List[Any] ): pass def _A ( self : Dict ): # Initialize image_processing UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Optional[int] = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase , UpperCamelCase :str = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) UpperCamelCase :int = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _A ( self : Tuple ): # Initialize image_processing UpperCamelCase :Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Union[str, Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Any = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase :Dict = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Optional[Any] = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _A ( self : Any ): # Initialize image_processing UpperCamelCase :Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :Tuple = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :List[str] = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase :Union[str, Any] = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :List[str] = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _A ( self : Optional[Any] ): # prepare image and target UpperCamelCase :int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: UpperCamelCase :str = json.loads(f.read() ) UpperCamelCase :List[Any] = {"""image_id""": 39_769, """annotations""": target} # encode them UpperCamelCase :Optional[int] = DeformableDetrImageProcessor() UpperCamelCase :Dict = image_processing(images=__lowerCamelCase , annotations=__lowerCamelCase , return_tensors="""pt""" ) # verify pixel values UpperCamelCase :Union[str, Any] = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["""pixel_values"""].shape , __lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __lowerCamelCase , atol=1E-4 ) ) # verify area UpperCamelCase :str = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __lowerCamelCase ) ) # verify boxes UpperCamelCase :List[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __lowerCamelCase ) UpperCamelCase :List[str] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __lowerCamelCase , atol=1E-3 ) ) # verify image_id UpperCamelCase :Tuple = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __lowerCamelCase ) ) # verify is_crowd UpperCamelCase :List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __lowerCamelCase ) ) # verify class_labels UpperCamelCase :Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __lowerCamelCase ) ) # verify orig_size UpperCamelCase :Dict = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __lowerCamelCase ) ) # verify size UpperCamelCase :int = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __lowerCamelCase ) ) @slow def _A ( self : str ): # prepare image, target and masks_path UpperCamelCase :Any = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: UpperCamelCase :Any = json.loads(f.read() ) UpperCamelCase :int = {"""file_name""": """000000039769.png""", """image_id""": 39_769, """segments_info""": target} UpperCamelCase :Any = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them UpperCamelCase :Tuple = DeformableDetrImageProcessor(format="""coco_panoptic""" ) UpperCamelCase :Dict = image_processing(images=__lowerCamelCase , annotations=__lowerCamelCase , masks_path=__lowerCamelCase , return_tensors="""pt""" ) # verify pixel values UpperCamelCase :Optional[int] = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["""pixel_values"""].shape , __lowerCamelCase ) UpperCamelCase :Optional[int] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __lowerCamelCase , atol=1E-4 ) ) # verify area UpperCamelCase :List[str] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __lowerCamelCase ) ) # verify boxes UpperCamelCase :List[str] = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __lowerCamelCase ) UpperCamelCase :List[Any] = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __lowerCamelCase , atol=1E-3 ) ) # verify image_id UpperCamelCase :str = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __lowerCamelCase ) ) # verify is_crowd UpperCamelCase :Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __lowerCamelCase ) ) # verify class_labels UpperCamelCase :List[Any] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __lowerCamelCase ) ) # verify masks UpperCamelCase :Union[str, Any] = 822_873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , __lowerCamelCase ) # verify orig_size UpperCamelCase :Tuple = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __lowerCamelCase ) ) # verify size UpperCamelCase :str = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __lowerCamelCase ) )
62
0
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __A =10 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): for i in range(UpperCamelCase__ , UpperCamelCase__ ): if array[i] == target: return i return -1 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Dict = 0 UpperCAmelCase__ : List[Any] = len(UpperCamelCase__ ) while left <= right: if right - left < precision: return lin_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Any = (left + right) // 3 + 1 UpperCAmelCase__ : Optional[int] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCAmelCase__ : List[str] = one_third - 1 elif array[two_third] < target: UpperCAmelCase__ : int = two_third + 1 else: UpperCAmelCase__ : Tuple = one_third + 1 UpperCAmelCase__ : List[Any] = two_third - 1 else: return -1 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): if left < right: if right - left < precision: return lin_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : str = (left + right) // 3 + 1 UpperCAmelCase__ : Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(UpperCamelCase__ , one_third - 1 , UpperCamelCase__ , UpperCamelCase__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , UpperCamelCase__ , UpperCamelCase__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __A =input('Enter numbers separated by comma:\n').strip() __A =[int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __A =int(input('Enter the number to be found in the list:\n').strip()) __A =ite_ternary_search(collection, target) __A =rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"""Iterative search: {target} found at positions: {resulta}""") print(f"""Recursive search: {target} found at positions: {resulta}""") else: print('Not found')
163
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __A =threading.Lock() __A =None __A ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __A =logging.WARNING __A =True def _UpperCamelCase ( ): UpperCAmelCase__ : str = os.getenv("""TRANSFORMERS_VERBOSITY""" , UpperCamelCase__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ''' f'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def _UpperCamelCase ( ): return __name__.split(""".""" )[0] def _UpperCamelCase ( ): return logging.getLogger(_get_library_name() ) def _UpperCamelCase ( ): global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return UpperCAmelCase__ : Optional[int] = logging.StreamHandler() # Set sys.stderr as stream. UpperCAmelCase__ : Any = sys.stderr.flush # Apply our default configuration to the library root logger. UpperCAmelCase__ : Optional[Any] = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) UpperCAmelCase__ : Union[str, Any] = False def _UpperCamelCase ( ): global _default_handler with _lock: if not _default_handler: return UpperCAmelCase__ : Optional[int] = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) UpperCAmelCase__ : Union[str, Any] = None def _UpperCamelCase ( ): return log_levels def _UpperCamelCase ( UpperCamelCase__ = None ): if name is None: UpperCAmelCase__ : Union[str, Any] = _get_library_name() _configure_library_root_logger() return logging.getLogger(UpperCamelCase__ ) def _UpperCamelCase ( ): _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def _UpperCamelCase ( UpperCamelCase__ ): _configure_library_root_logger() _get_library_root_logger().setLevel(UpperCamelCase__ ) def _UpperCamelCase ( ): return set_verbosity(UpperCamelCase__ ) def _UpperCamelCase ( ): return set_verbosity(UpperCamelCase__ ) def _UpperCamelCase ( ): return set_verbosity(UpperCamelCase__ ) def _UpperCamelCase ( ): return set_verbosity(UpperCamelCase__ ) def _UpperCamelCase ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def _UpperCamelCase ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def _UpperCamelCase ( UpperCamelCase__ ): _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(UpperCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ ): _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(UpperCamelCase__ ) def _UpperCamelCase ( ): _configure_library_root_logger() UpperCAmelCase__ : str = False def _UpperCamelCase ( ): _configure_library_root_logger() UpperCAmelCase__ : Optional[int] = True def _UpperCamelCase ( ): UpperCAmelCase__ : str = _get_library_root_logger().handlers for handler in handlers: UpperCAmelCase__ : List[str] = logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s""" ) handler.setFormatter(UpperCamelCase__ ) def _UpperCamelCase ( ): UpperCAmelCase__ : Optional[int] = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(UpperCamelCase__ ) def _UpperCamelCase ( self , *UpperCamelCase__ , **UpperCamelCase__ ): UpperCAmelCase__ : Optional[Any] = os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS""" , UpperCamelCase__ ) if no_advisory_warnings: return self.warning(*UpperCamelCase__ , **UpperCamelCase__ ) __A =warning_advice @functools.lru_cache(UpperCamelCase__ ) def _UpperCamelCase ( self , *UpperCamelCase__ , **UpperCamelCase__ ): self.warning(*UpperCamelCase__ , **UpperCamelCase__ ) __A =warning_once class _snake_case : def __init__( self , *_lowerCamelCase , **_lowerCamelCase): # pylint: disable=unused-argument UpperCAmelCase__ : Union[str, Any] = args[0] if args else None def __iter__( self): return iter(self._iterator) def __getattr__( self , _lowerCamelCase): def empty_fn(*_lowerCamelCase , **_lowerCamelCase): # pylint: disable=unused-argument return return empty_fn def __enter__( self): return self def __exit__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase): return class _snake_case : def __call__( self , *_lowerCamelCase , **_lowerCamelCase): if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase) def snake_case__ ( self , *_lowerCamelCase , **_lowerCamelCase): UpperCAmelCase__ : Tuple = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase) def snake_case__ ( self): if _tqdm_active: return tqdm_lib.tqdm.get_lock() __A =_tqdm_cls() def _UpperCamelCase ( ): global _tqdm_active return bool(_tqdm_active ) def _UpperCamelCase ( ): global _tqdm_active UpperCAmelCase__ : Optional[Any] = True hf_hub_utils.enable_progress_bars() def _UpperCamelCase ( ): global _tqdm_active UpperCAmelCase__ : List[str] = False hf_hub_utils.disable_progress_bars()
163
1
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): # Initialise PyTorch model _lowerCamelCase : Any = FunnelConfig.from_json_file(lowercase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) _lowerCamelCase : Optional[int] = FunnelBaseModel(lowercase__ ) if base_model else FunnelModel(lowercase__ ) # Load weights from tf checkpoint load_tf_weights_in_funnel(lowercase__ , lowercase__ , lowercase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase__ ) 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( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--base_model""", action="""store_true""", help="""Whether you want just the base model (no decoder) or not.""" ) lowercase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase__ = { """configuration_mega""": ["""MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegaConfig""", """MegaOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ """MEGA_PRETRAINED_MODEL_ARCHIVE_LIST""", """MegaForCausalLM""", """MegaForMaskedLM""", """MegaForMultipleChoice""", """MegaForQuestionAnswering""", """MegaForSequenceClassification""", """MegaForTokenClassification""", """MegaModel""", """MegaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
12
0
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _a = logging.get_logger(__name__) _a = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _a = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } _a = {'''allegro/herbert-base-cased''': 514} _a = {} class __lowerCamelCase ( _UpperCamelCase): """simple docstring""" UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_INIT_CONFIGURATION UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = HerbertTokenizer def __init__( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase="<s>" , UpperCAmelCase="<unk>" , UpperCAmelCase="<pad>" , UpperCAmelCase="<mask>" , UpperCAmelCase="</s>" , **UpperCAmelCase , ): """simple docstring""" super().__init__( _UpperCAmelCase , _UpperCAmelCase , tokenizer_file=_UpperCAmelCase , cls_token=_UpperCAmelCase , unk_token=_UpperCAmelCase , pad_token=_UpperCAmelCase , mask_token=_UpperCAmelCase , sep_token=_UpperCAmelCase , **_UpperCAmelCase , ) def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase = None ): """simple docstring""" _UpperCAmelCase = [self.cls_token_id] _UpperCAmelCase = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase , token_ids_a=_UpperCAmelCase , already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1] + ([0] * len(_UpperCAmelCase )) + [1] def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase = None ): """simple docstring""" _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase = None ): """simple docstring""" _UpperCAmelCase = self._tokenizer.model.save(_UpperCAmelCase , name=_UpperCAmelCase ) return tuple(_UpperCAmelCase )
39
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class SCREAMING_SNAKE_CASE__ (unittest.TestCase ): def snake_case_ ( self): lowercase__ : List[str] = 'laion/clap-htsat-unfused' lowercase__ : List[Any] = tempfile.mkdtemp() def snake_case_ ( self , **a): return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def snake_case_ ( self , **a): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def snake_case_ ( self): shutil.rmtree(self.tmpdirname) def snake_case_ ( self): lowercase__ : Optional[Any] = self.get_tokenizer() lowercase__ : Optional[int] = self.get_feature_extractor() lowercase__ : Optional[Any] = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) lowercase__ : Union[str, Any] = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def snake_case_ ( self): lowercase__ : Tuple = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) lowercase__ : Dict = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') lowercase__ : str = self.get_feature_extractor(do_normalize=a , padding_value=1.0) lowercase__ : Optional[int] = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def snake_case_ ( self): lowercase__ : Any = self.get_feature_extractor() lowercase__ : int = self.get_tokenizer() lowercase__ : Optional[int] = ClapProcessor(tokenizer=a , feature_extractor=a) lowercase__ : Dict = floats_list((3, 1000)) lowercase__ : Union[str, Any] = feature_extractor(a , return_tensors='np') lowercase__ : str = processor(audios=a , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def snake_case_ ( self): lowercase__ : Dict = self.get_feature_extractor() lowercase__ : Tuple = self.get_tokenizer() lowercase__ : str = ClapProcessor(tokenizer=a , feature_extractor=a) lowercase__ : Dict = 'This is a test string' lowercase__ : Optional[Any] = processor(text=a) lowercase__ : List[Any] = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def snake_case_ ( self): lowercase__ : Any = self.get_feature_extractor() lowercase__ : Union[str, Any] = self.get_tokenizer() lowercase__ : Dict = ClapProcessor(tokenizer=a , feature_extractor=a) lowercase__ : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase__ : int = processor.batch_decode(a) lowercase__ : int = tokenizer.batch_decode(a) self.assertListEqual(a , a) def snake_case_ ( self): lowercase__ : Optional[Any] = self.get_feature_extractor() lowercase__ : Dict = self.get_tokenizer() lowercase__ : List[Any] = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
216
from __future__ import annotations from collections.abc import Callable def snake_case__ ( SCREAMING_SNAKE_CASE_ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int = 100 , ): '''simple docstring''' lowercase__ : Tuple = x_start lowercase__ : Tuple = fnc(SCREAMING_SNAKE_CASE_ ) lowercase__ : List[Any] = 0.0 for _ in range(SCREAMING_SNAKE_CASE_ ): # Approximates small segments of curve as linear and solve # for trapezoidal area lowercase__ : Any = (x_end - x_start) / steps + xa lowercase__ : Optional[Any] = fnc(SCREAMING_SNAKE_CASE_ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step lowercase__ : Any = xa lowercase__ : str = fxa return area if __name__ == "__main__": def snake_case__ ( SCREAMING_SNAKE_CASE_ : Tuple ): '''simple docstring''' return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') snake_case_ = 10 while i <= 100_000: print(F'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
216
1
def lowerCamelCase__ ( a ) -> int: if not isinstance(a , a ): _A: List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(a ) if number < 1: _A: List[Any] = f"""Input value of [number={number}] must be > 0""" raise ValueError(a ) _A: Dict = 1 for i in range(1 , a ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
121
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Any = { 'huggingface/informer-tourism-monthly': ( 'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json' ), # See all Informer models at https://huggingface.co/models?filter=informer } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : List[Any] = '''informer''' __UpperCamelCase : List[str] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[Any] , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : str = "student_t" , lowerCAmelCase_ : str = "nll" , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : List[int] = None , lowerCAmelCase_ : Optional[Union[str, bool]] = "mean" , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[List[int]] = None , lowerCAmelCase_ : Optional[List[int]] = None , lowerCAmelCase_ : int = 6_4 , lowerCAmelCase_ : int = 3_2 , lowerCAmelCase_ : int = 3_2 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : str = "gelu" , lowerCAmelCase_ : float = 0.05 , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : int = 1_0_0 , lowerCAmelCase_ : float = 0.02 , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : str = "prob" , lowerCAmelCase_ : int = 5 , lowerCAmelCase_ : bool = True , **lowerCAmelCase_ : str , ): """simple docstring""" # time series specific configuration _A: Optional[Any] = prediction_length _A: Optional[Any] = context_length or prediction_length _A: Dict = distribution_output _A: List[str] = loss _A: int = input_size _A: List[str] = num_time_features _A: Optional[Any] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] _A: str = scaling _A: Optional[Any] = num_dynamic_real_features _A: List[Any] = num_static_real_features _A: Tuple = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(lowerCAmelCase_ ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) _A: str = cardinality else: _A: Union[str, Any] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(lowerCAmelCase_ ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) _A: List[str] = embedding_dimension else: _A: Union[str, Any] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] _A: int = num_parallel_samples # Transformer architecture configuration _A: Union[str, Any] = input_size * len(self.lags_sequence ) + self._number_of_features _A: Union[str, Any] = d_model _A: Optional[Any] = encoder_attention_heads _A: Optional[Any] = decoder_attention_heads _A: Optional[Any] = encoder_ffn_dim _A: Union[str, Any] = decoder_ffn_dim _A: Any = encoder_layers _A: str = decoder_layers _A: List[str] = dropout _A: Any = attention_dropout _A: Optional[int] = activation_dropout _A: List[Any] = encoder_layerdrop _A: str = decoder_layerdrop _A: int = activation_function _A: Tuple = init_std _A: Union[str, Any] = use_cache # Informer _A: Union[str, Any] = attention_type _A: str = sampling_factor _A: List[str] = distil super().__init__(is_encoder_decoder=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : List[str] ): """simple docstring""" return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
121
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE :List[Any] = { 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], 'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'AdaptiveEmbedding', 'TransfoXLForSequenceClassification', 'TransfoXLLMHeadModel', 'TransfoXLModel', 'TransfoXLPreTrainedModel', 'load_tf_weights_in_transfo_xl', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Dict = [ 'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAdaptiveEmbedding', 'TFTransfoXLForSequenceClassification', 'TFTransfoXLLMHeadModel', 'TFTransfoXLMainLayer', 'TFTransfoXLModel', 'TFTransfoXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
124
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE :int = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Dict = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :int = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[int] = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys SCREAMING_SNAKE_CASE :int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
124
1
_lowercase: List[Any] = "Alexander Joslin" import operator as op from .stack import Stack def a( A : str ) -> int: """simple docstring""" a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} a = Stack() a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(A ) ) elif i in operators: # RULE 2 operator_stack.push(A ) elif i == ")": # RULE 4 a = operator_stack.peek() operator_stack.pop() a = operand_stack.peek() operand_stack.pop() a = operand_stack.peek() operand_stack.pop() a = operators[opr](A , A ) operand_stack.push(A ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": _lowercase: Dict = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
227
import cmath import math def a( A : float , A : float , A : float , A : float ) -> complex: """simple docstring""" a = math.radians(A ) a = math.radians(A ) # Convert voltage and current to rectangular form a = cmath.rect(A , A ) a = cmath.rect(A , A ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
227
1
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
287
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def a__ ( lowercase : Tuple ) -> Dict: """simple docstring""" _UpperCamelCase = int(lowercase ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = t // 3600, (t // 60) % 60, t % 60 return F"""{h}:{m:02d}:{s:02d}""" if h != 0 else F"""{m:02d}:{s:02d}""" def a__ ( lowercase : List[Any], lowercase : Dict, lowercase : Optional[int], lowercase : Union[str, Any], lowercase : Any=300 ) -> Any: """simple docstring""" return F""" <div> {prefix} <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress> {label} </div> """ def a__ ( lowercase : Optional[Any] ) -> Any: """simple docstring""" _UpperCamelCase = '''<table border="1" class="dataframe">\n''' html_code += """ <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += F""" <th>{i}</th>\n""" html_code += " </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for elt in line: _UpperCamelCase = F"""{elt:.6f}""" if isinstance(lowercase, lowercase ) else str(lowercase ) html_code += F""" <td>{elt}</td>\n""" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code class __lowerCAmelCase : """simple docstring""" _snake_case : str = 5 _snake_case : Optional[int] = 0.2 def __init__( self : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Optional["NotebookTrainingTracker"] = None , lowerCAmelCase__ : int = 300 , ) -> int: '''simple docstring''' _UpperCamelCase = total _UpperCamelCase = '''''' if prefix is None else prefix _UpperCamelCase = leave _UpperCamelCase = parent _UpperCamelCase = width _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None def snake_case__ ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : str = None ) -> Dict: '''simple docstring''' _UpperCamelCase = value if comment is not None: _UpperCamelCase = comment if self.last_value is None: _UpperCamelCase = _UpperCamelCase = time.time() _UpperCamelCase = _UpperCamelCase = value _UpperCamelCase = _UpperCamelCase = None _UpperCamelCase = self.warmup _UpperCamelCase = 1 self.update_bar(lowerCAmelCase__ ) elif value <= self.last_value and not force_update: return elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total ): if self.first_calls > 0: self.first_calls -= 1 _UpperCamelCase = time.time() _UpperCamelCase = current_time - self.start_time # We could have value = self.start_value if the update is called twixe with the same start value. if value > self.start_value: _UpperCamelCase = self.elapsed_time / (value - self.start_value) else: _UpperCamelCase = None if value >= self.total: _UpperCamelCase = self.total _UpperCamelCase = None if not self.leave: self.close() elif self.average_time_per_item is not None: _UpperCamelCase = self.average_time_per_item * (self.total - value) self.update_bar(lowerCAmelCase__ ) _UpperCamelCase = value _UpperCamelCase = current_time if self.average_time_per_item is None: _UpperCamelCase = 1 else: _UpperCamelCase = max(int(self.update_every / self.average_time_per_item ) , 1 ) def snake_case__ ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple=None ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = ''' ''' * (len(str(self.total ) ) - len(str(lowerCAmelCase__ ) )) + str(lowerCAmelCase__ ) if self.elapsed_time is None: _UpperCamelCase = f"""[{spaced_value}/{self.total} : < :""" elif self.predicted_remaining is None: _UpperCamelCase = f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time )}""" else: _UpperCamelCase = ( f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <""" f""" {format_time(self.predicted_remaining )}""" ) self.label += f""", {1/self.average_time_per_item:.2f} it/s""" self.label += "]" if self.comment is None or len(self.comment ) == 0 else f""", {self.comment}]""" self.display() def snake_case__ ( self : List[Any] ) -> Tuple: '''simple docstring''' _UpperCamelCase = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.parent is not None: # If this is a child bar, the parent will take care of the display. self.parent.display() return if self.output is None: _UpperCamelCase = disp.display(disp.HTML(self.html_code ) , display_id=lowerCAmelCase__ ) else: self.output.update(disp.HTML(self.html_code ) ) def snake_case__ ( self : Tuple ) -> Any: '''simple docstring''' if self.parent is None and self.output is not None: self.output.update(disp.HTML('''''' ) ) class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]=None ) -> Dict: '''simple docstring''' super().__init__(lowerCAmelCase__ ) _UpperCamelCase = None if column_names is None else [column_names] _UpperCamelCase = None def snake_case__ ( self : List[Any] ) -> Any: '''simple docstring''' _UpperCamelCase = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.inner_table is not None: self.html_code += text_to_html_table(self.inner_table ) if self.child_bar is not None: self.html_code += self.child_bar.html_code if self.output is None: _UpperCamelCase = disp.display(disp.HTML(self.html_code ) , display_id=lowerCAmelCase__ ) else: self.output.update(disp.HTML(self.html_code ) ) def snake_case__ ( self : Optional[int] , lowerCAmelCase__ : int ) -> Union[str, Any]: '''simple docstring''' if self.inner_table is None: _UpperCamelCase = [list(values.keys() ), list(values.values() )] else: _UpperCamelCase = self.inner_table[0] if len(self.inner_table ) == 1: # We give a chance to update the column names at the first iteration for key in values.keys(): if key not in columns: columns.append(lowerCAmelCase__ ) _UpperCamelCase = columns self.inner_table.append([values[c] for c in columns] ) def snake_case__ ( self : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : List[str]=300 ) -> int: '''simple docstring''' _UpperCamelCase = NotebookProgressBar(lowerCAmelCase__ , prefix=lowerCAmelCase__ , parent=self , width=lowerCAmelCase__ ) return self.child_bar def snake_case__ ( self : Any ) -> str: '''simple docstring''' _UpperCamelCase = None self.display() class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" def __init__( self : str ) -> Optional[int]: '''simple docstring''' _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = False def snake_case__ ( self : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : str , **lowerCAmelCase__ : Any ) -> Dict: '''simple docstring''' _UpperCamelCase = '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step''' _UpperCamelCase = 0 _UpperCamelCase = 0 _UpperCamelCase = [self.first_column] + ['''Training Loss'''] if args.evaluation_strategy != IntervalStrategy.NO: column_names.append('''Validation Loss''' ) _UpperCamelCase = NotebookTrainingTracker(state.max_steps , lowerCAmelCase__ ) def snake_case__ ( self : Optional[int] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , **lowerCAmelCase__ : Dict ) -> Dict: '''simple docstring''' _UpperCamelCase = int(state.epoch ) if int(state.epoch ) == state.epoch else f"""{state.epoch:.2f}""" self.training_tracker.update( state.global_step + 1 , comment=f"""Epoch {epoch}/{state.num_train_epochs}""" , force_update=self._force_next_update , ) _UpperCamelCase = False def snake_case__ ( self : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]=None , **lowerCAmelCase__ : Dict ) -> Dict: '''simple docstring''' if not has_length(lowerCAmelCase__ ): return if self.prediction_bar is None: if self.training_tracker is not None: _UpperCamelCase = self.training_tracker.add_child(len(lowerCAmelCase__ ) ) else: _UpperCamelCase = NotebookProgressBar(len(lowerCAmelCase__ ) ) self.prediction_bar.update(1 ) else: self.prediction_bar.update(self.prediction_bar.value + 1 ) def snake_case__ ( self : Optional[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict , **lowerCAmelCase__ : Any ) -> Optional[int]: '''simple docstring''' if self.prediction_bar is not None: self.prediction_bar.close() _UpperCamelCase = None def snake_case__ ( self : Optional[int] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int]=None , **lowerCAmelCase__ : Optional[int] ) -> Tuple: '''simple docstring''' if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs: _UpperCamelCase = {'''Training Loss''': logs['''loss''']} # First column is necessarily Step sine we're not in epoch eval strategy _UpperCamelCase = state.global_step self.training_tracker.write_line(lowerCAmelCase__ ) def snake_case__ ( self : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any]=None , **lowerCAmelCase__ : List[str] ) -> List[str]: '''simple docstring''' if self.training_tracker is not None: _UpperCamelCase = {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''} for log in reversed(state.log_history ): if "loss" in log: _UpperCamelCase = log['''loss'''] break if self.first_column == "Epoch": _UpperCamelCase = int(state.epoch ) else: _UpperCamelCase = state.global_step _UpperCamelCase = '''eval''' for k in metrics: if k.endswith('''_loss''' ): _UpperCamelCase = re.sub(r'''\_loss$''' , '''''' , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop('''total_flos''' , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop('''epoch''' , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop(f"""{metric_key_prefix}_runtime""" , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop(f"""{metric_key_prefix}_samples_per_second""" , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop(f"""{metric_key_prefix}_steps_per_second""" , lowerCAmelCase__ ) _UpperCamelCase = metrics.pop(f"""{metric_key_prefix}_jit_compilation_time""" , lowerCAmelCase__ ) for k, v in metrics.items(): if k == f"""{metric_key_prefix}_loss""": _UpperCamelCase = v else: _UpperCamelCase = k.split('''_''' ) _UpperCamelCase = ''' '''.join([part.capitalize() for part in splits[1:]] ) _UpperCamelCase = v self.training_tracker.write_line(lowerCAmelCase__ ) self.training_tracker.remove_child() _UpperCamelCase = None # Evaluation takes a long time so we should force the next update. _UpperCamelCase = True def snake_case__ ( self : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any , **lowerCAmelCase__ : List[str] ) -> Optional[Any]: '''simple docstring''' self.training_tracker.update( state.global_step , comment=f"""Epoch {int(state.epoch )}/{state.num_train_epochs}""" , force_update=lowerCAmelCase__ ) _UpperCamelCase = None
287
1
'''simple docstring''' import torch def __lowercase ( ) -> List[Any]: '''simple docstring''' if torch.cuda.is_available(): _A = torch.cuda.device_count() else: _A = 0 print(F'''Successfully ran on {num_gpus} GPUs''' ) if __name__ == "__main__": main()
79
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' A__ = ShapEImgaImgPipeline A__ = ['''image'''] A__ = ['''image'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def lowerCamelCase__ (self : Optional[Any] ) -> List[str]: """simple docstring""" return 32 @property def lowerCamelCase__ (self : str ) -> Any: """simple docstring""" return 32 @property def lowerCamelCase__ (self : str ) -> List[str]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCamelCase__ (self : List[Any] ) -> Any: """simple docstring""" return 8 @property def lowerCamelCase__ (self : int ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(_UpperCAmelCase ) return model @property def lowerCamelCase__ (self : Any ) -> List[Any]: """simple docstring""" lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=_UpperCAmelCase , do_normalize=_UpperCAmelCase , do_resize=_UpperCAmelCase , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=224 , ) return image_processor @property def lowerCamelCase__ (self : int ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) lowercase__ = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } lowercase__ = PriorTransformer(**_UpperCAmelCase ) return model @property def lowerCamelCase__ (self : Union[str, Any] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) lowercase__ = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**_UpperCAmelCase ) return model def lowerCamelCase__ (self : int ) -> Optional[int]: """simple docstring""" lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=_UpperCAmelCase , clip_sample=_UpperCAmelCase , clip_sample_range=1.0 , ) lowercase__ = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def lowerCamelCase__ (self : Dict , _UpperCAmelCase : List[Any] , _UpperCAmelCase : str=0 ) -> str: """simple docstring""" lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) if str(_UpperCAmelCase ).startswith("""mps""" ): lowercase__ = torch.manual_seed(_UpperCAmelCase ) else: lowercase__ = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) lowercase__ = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def lowerCamelCase__ (self : str ) -> List[str]: """simple docstring""" lowercase__ = """cpu""" lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**_UpperCAmelCase ) lowercase__ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) lowercase__ = pipe(**self.get_dummy_inputs(_UpperCAmelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ (self : str ) -> Any: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCamelCase__ (self : Optional[int] ) -> str: """simple docstring""" lowercase__ = torch_device == """cpu""" lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_UpperCAmelCase , relax_max_difference=_UpperCAmelCase , ) def lowerCamelCase__ (self : Union[str, Any] ) -> int: """simple docstring""" lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**_UpperCAmelCase ) lowercase__ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(_UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ (self : Dict ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ (self : Any ) -> str: """simple docstring""" lowercase__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) lowercase__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) lowercase__ = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) lowercase__ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) lowercase__ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) lowercase__ = pipe( _UpperCAmelCase , generator=_UpperCAmelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase )
305
0
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def __lowerCamelCase ( __a :List[Any] , __a :List[Any] , __a :Any ) -> Tuple: """simple docstring""" A__ = LxmertConfig.from_json_file(lowerCamelCase_ ) print(F'Building PyTorch model from configuration: {config}' ) A__ = LxmertForPreTraining(lowerCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowerCamelCase_ ) if __name__ == "__main__": A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A : Dict = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
356
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
276
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __snake_case = logging.get_logger(__name__) __snake_case = { '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class lowercase ( A__ ): """simple docstring""" _a = 'deberta-v2' def __init__( self , UpperCamelCase_=128100 , UpperCamelCase_=1536 , UpperCamelCase_=24 , UpperCamelCase_=24 , UpperCamelCase_=6144 , UpperCamelCase_="gelu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=512 , UpperCamelCase_=0 , UpperCamelCase_=0.02 , UpperCamelCase_=1e-7 , UpperCamelCase_=False , UpperCamelCase_=-1 , UpperCamelCase_=0 , UpperCamelCase_=True , UpperCamelCase_=None , UpperCamelCase_=0 , UpperCamelCase_="gelu" , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = hidden_size UpperCamelCase__ :Union[str, Any] = num_hidden_layers UpperCamelCase__ :List[str] = num_attention_heads UpperCamelCase__ :Optional[Any] = intermediate_size UpperCamelCase__ :int = hidden_act UpperCamelCase__ :Dict = hidden_dropout_prob UpperCamelCase__ :str = attention_probs_dropout_prob UpperCamelCase__ :Union[str, Any] = max_position_embeddings UpperCamelCase__ :Dict = type_vocab_size UpperCamelCase__ :Dict = initializer_range UpperCamelCase__ :Any = relative_attention UpperCamelCase__ :int = max_relative_positions UpperCamelCase__ :List[Any] = pad_token_id UpperCamelCase__ :List[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase_ ) == str: UpperCamelCase__ :Optional[Any] = [x.strip() for x in pos_att_type.lower().split('''|''' )] UpperCamelCase__ :List[str] = pos_att_type UpperCamelCase__ :Dict = vocab_size UpperCamelCase__ :Optional[Any] = layer_norm_eps UpperCamelCase__ :Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase_ ) UpperCamelCase__ :List[Any] = pooler_dropout UpperCamelCase__ :str = pooler_hidden_act class lowercase ( A__ ): """simple docstring""" @property def lowerCAmelCase__ ( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase__ :str = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase__ :Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return 12 def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = -1 , UpperCamelCase_ = -1 , UpperCamelCase_ = -1 , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = 3 , UpperCamelCase_ = 40 , UpperCamelCase_ = 40 , UpperCamelCase_ = None , ): '''simple docstring''' UpperCamelCase__ :List[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase_ , framework=UpperCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
97
'''simple docstring''' from PIL import Image def a ( __a , __a ) -> Image: '''simple docstring''' def brightness(__a ) -> float: return 128 + level + (c - 128) if not -2_5_5.0 <= level <= 2_5_5.0: raise ValueError('''level must be between -255.0 (black) and 255.0 (white)''' ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 __snake_case = change_brightness(img, 100) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
97
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : str = logging.get_logger(__name__) lowerCAmelCase_ : str = { '''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 ( __a ): snake_case : Tuple = """funnel""" snake_case : Tuple = { """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", } def __init__(self , lowerCAmelCase__=3_0_5_2_2 , lowerCAmelCase__=[4, 4, 4] , lowerCAmelCase__=None , lowerCAmelCase__=2 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=6_4 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu_new" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__=None , lowerCAmelCase__=1e-9 , lowerCAmelCase__="mean" , lowerCAmelCase__="relative_shift" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , **lowerCAmelCase__ , ): _UpperCAmelCase : Union[str, Any] = vocab_size _UpperCAmelCase : List[str] = block_sizes _UpperCAmelCase : Dict = [1] * len(lowerCAmelCase__ ) if block_repeats is None else block_repeats assert len(lowerCAmelCase__ ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." _UpperCAmelCase : Union[str, Any] = num_decoder_layers _UpperCAmelCase : int = d_model _UpperCAmelCase : Union[str, Any] = n_head _UpperCAmelCase : List[Any] = d_head _UpperCAmelCase : Optional[int] = d_inner _UpperCAmelCase : List[str] = hidden_act _UpperCAmelCase : Tuple = hidden_dropout _UpperCAmelCase : Optional[Any] = attention_dropout _UpperCAmelCase : int = activation_dropout _UpperCAmelCase : Optional[Any] = initializer_range _UpperCAmelCase : List[str] = initializer_std _UpperCAmelCase : int = layer_norm_eps assert pooling_type in [ "mean", "max", ], F"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported." _UpperCAmelCase : Optional[Any] = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported." _UpperCAmelCase : str = attention_type _UpperCAmelCase : Optional[Any] = separate_cls _UpperCAmelCase : List[Any] = truncate_seq _UpperCAmelCase : List[Any] = pool_q_only super().__init__(**lowerCAmelCase__ ) @property def snake_case_ (self ): return sum(self.block_sizes ) @num_hidden_layers.setter def snake_case_ (self , lowerCAmelCase__ ): raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.""" ) @property def snake_case_ (self ): return len(self.block_sizes ) @num_blocks.setter def snake_case_ (self , lowerCAmelCase__ ): raise NotImplementedError("""This model does not support the setting of `num_blocks`. Please set `block_sizes`.""" )
170
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : List[str] = logging.get_logger(__name__) lowerCAmelCase_ : Union[str, Any] = { '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''', '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''', } class __lowerCAmelCase ( __a ): snake_case : Optional[Any] = """luke""" def __init__(self , lowerCAmelCase__=5_0_2_6_7 , lowerCAmelCase__=5_0_0_0_0_0 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=2 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=1e-12 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , **lowerCAmelCase__ , ): super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) _UpperCAmelCase : Any = vocab_size _UpperCAmelCase : Any = entity_vocab_size _UpperCAmelCase : List[Any] = hidden_size _UpperCAmelCase : Dict = entity_emb_size _UpperCAmelCase : Dict = num_hidden_layers _UpperCAmelCase : List[str] = num_attention_heads _UpperCAmelCase : Optional[int] = hidden_act _UpperCAmelCase : str = intermediate_size _UpperCAmelCase : Dict = hidden_dropout_prob _UpperCAmelCase : List[str] = attention_probs_dropout_prob _UpperCAmelCase : List[str] = max_position_embeddings _UpperCAmelCase : Tuple = type_vocab_size _UpperCAmelCase : Any = initializer_range _UpperCAmelCase : Union[str, Any] = layer_norm_eps _UpperCAmelCase : Optional[int] = use_entity_aware_attention _UpperCAmelCase : Optional[Any] = classifier_dropout
170
1
'''simple docstring''' import math def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False UpperCAmelCase__ = range(3 , int(math.sqrt(SCREAMING_SNAKE_CASE__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str]=1 , **SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' UpperCAmelCase__ = factor * value UpperCAmelCase__ = value while not is_prime(SCREAMING_SNAKE_CASE__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **SCREAMING_SNAKE_CASE__ ) return value
346
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : int = MgpstrTokenizer lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : Optional[int] = {} lowerCAmelCase_ : Any = False def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" super().setUp() # fmt: off UpperCAmelCase__ = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on UpperCAmelCase__ = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) ) UpperCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + """\n""" ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , **_UpperCAmelCase : Optional[Any] ): """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , _UpperCAmelCase : Tuple ): """simple docstring""" UpperCAmelCase__ = """tester""" UpperCAmelCase__ = """tester""" return input_text, output_text @unittest.skip("""MGP-STR always lower cases letters.""" ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = self.get_tokenizers(do_lower_case=_UpperCAmelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): UpperCAmelCase__ = """[SPECIAL_TOKEN]""" tokenizer.add_special_tokens({"""cls_token""": special_token} ) UpperCAmelCase__ = tokenizer.encode([special_token] , add_special_tokens=_UpperCAmelCase ) self.assertEqual(len(_UpperCAmelCase ) , 1 ) UpperCAmelCase__ = tokenizer.decode(_UpperCAmelCase , skip_special_tokens=_UpperCAmelCase ) self.assertTrue(special_token not in decoded ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" UpperCAmelCase__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): UpperCAmelCase__ , UpperCAmelCase__ = self.get_input_output_texts(_UpperCAmelCase ) UpperCAmelCase__ = tokenizer.tokenize(_UpperCAmelCase ) UpperCAmelCase__ = tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) UpperCAmelCase__ = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) UpperCAmelCase__ = tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertNotEqual(len(_UpperCAmelCase ) , 0 ) UpperCAmelCase__ = tokenizer.decode(_UpperCAmelCase ) self.assertIsInstance(_UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(text_a.replace(""" """ , """""" ) , _UpperCAmelCase ) @unittest.skip("""MGP-STR tokenizer only handles one sequence.""" ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" pass @unittest.skip("""inputs cannot be pretokenized in MgpstrTokenizer""" ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" pass
346
1
"""simple docstring""" import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case__ : Tuple = logging.get_logger(__name__) snake_case__ : Optional[int] = { '''vocab_file''': '''vocab.txt''', '''merges_file''': '''bpe.codes''', } snake_case__ : Any = { '''vocab_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''', }, '''merges_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''', }, } snake_case__ : str = { '''vinai/phobert-base''': 256, '''vinai/phobert-large''': 256, } def _snake_case ( _snake_case : List[Any] ): lowerCAmelCase : int = set() lowerCAmelCase : Union[str, Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCAmelCase : Dict = char lowerCAmelCase : Union[str, Any] = set(_snake_case ) return pairs class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str="<s>" , UpperCamelCase_ : Optional[int]="</s>" , UpperCamelCase_ : int="</s>" , UpperCamelCase_ : Any="<s>" , UpperCamelCase_ : int="<unk>" , UpperCamelCase_ : Dict="<pad>" , UpperCamelCase_ : str="<mask>" , **UpperCamelCase_ : Optional[Any] , ): super().__init__( bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Any = vocab_file lowerCAmelCase : Dict = merges_file lowerCAmelCase : List[str] = {} lowerCAmelCase : List[Any] = 0 lowerCAmelCase : str = 1 lowerCAmelCase : Any = 2 lowerCAmelCase : Optional[int] = 3 self.add_from_file(UpperCamelCase_ ) lowerCAmelCase : Any = {v: k for k, v in self.encoder.items()} with open(UpperCamelCase_ , encoding='''utf-8''' ) as merges_handle: lowerCAmelCase : List[Any] = merges_handle.read().split('''\n''' )[:-1] lowerCAmelCase : List[Any] = [tuple(merge.split()[:-1] ) for merge in merges] lowerCAmelCase : Any = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowerCAmelCase : Optional[Any] = {} def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase : Union[str, Any] = [self.cls_token_id] lowerCAmelCase : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1] def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Optional[int] = [self.sep_token_id] lowerCAmelCase : List[str] = [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] @property def lowerCamelCase__ ( self : Any ): return len(self.encoder ) def lowerCamelCase__ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : Optional[int] ): if token in self.cache: return self.cache[token] lowerCAmelCase : str = tuple(UpperCamelCase_ ) lowerCAmelCase : List[str] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) lowerCAmelCase : Tuple = get_pairs(UpperCamelCase_ ) if not pairs: return token while True: lowerCAmelCase : Optional[int] = min(UpperCamelCase_ , key=lambda UpperCamelCase_ : self.bpe_ranks.get(UpperCamelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowerCAmelCase : Any = bigram lowerCAmelCase : Dict = [] lowerCAmelCase : Any = 0 while i < len(UpperCamelCase_ ): try: lowerCAmelCase : Optional[Any] = word.index(UpperCamelCase_ , UpperCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCAmelCase : Tuple = j if word[i] == first and i < len(UpperCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCAmelCase : Dict = tuple(UpperCamelCase_ ) lowerCAmelCase : Dict = new_word if len(UpperCamelCase_ ) == 1: break else: lowerCAmelCase : Optional[int] = get_pairs(UpperCamelCase_ ) lowerCAmelCase : Tuple = '''@@ '''.join(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = word[:-4] lowerCAmelCase : int = word return word def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : Tuple ): lowerCAmelCase : Tuple = [] lowerCAmelCase : Dict = re.findall(r'''\S+\n?''' , UpperCamelCase_ ) for token in words: split_tokens.extend(list(self.bpe(UpperCamelCase_ ).split(''' ''' ) ) ) return split_tokens def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : Optional[int] ): return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : Union[str, Any] ): return self.decoder.get(UpperCamelCase_ , self.unk_token ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Any ): lowerCAmelCase : Dict = ''' '''.join(UpperCamelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase : Union[str, Any] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase : Tuple = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ): copyfile(self.vocab_file , UpperCamelCase_ ) if os.path.abspath(self.merges_file ) != os.path.abspath(UpperCamelCase_ ): copyfile(self.merges_file , UpperCamelCase_ ) return out_vocab_file, out_merge_file def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : Optional[int] ): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): try: with open(UpperCamelCase_ , '''r''' , encoding='''utf-8''' ) as fd: self.add_from_file(UpperCamelCase_ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(F'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return lowerCAmelCase : List[Any] = f.readlines() for lineTmp in lines: lowerCAmelCase : Any = lineTmp.strip() lowerCAmelCase : List[Any] = line.rfind(''' ''' ) if idx == -1: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\'''' ) lowerCAmelCase : Dict = line[:idx] lowerCAmelCase : List[str] = len(self.encoder )
364
"""simple docstring""" import numpy as np from PIL import Image def _snake_case ( _snake_case : np.ndarray , _snake_case : int , _snake_case : int ): lowerCAmelCase : Dict = np.array(_snake_case ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input array is not a square matrix''' ) lowerCAmelCase : int = 0 lowerCAmelCase : Dict = 0 lowerCAmelCase : str = 0 lowerCAmelCase : Union[str, Any] = 0 # compute the shape of the output matrix lowerCAmelCase : Tuple = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape lowerCAmelCase : Dict = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix lowerCAmelCase : List[Any] = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 lowerCAmelCase : int = 0 lowerCAmelCase : Tuple = 0 return updated_arr def _snake_case ( _snake_case : np.ndarray , _snake_case : int , _snake_case : int ): lowerCAmelCase : Union[str, Any] = np.array(_snake_case ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input array is not a square matrix''' ) lowerCAmelCase : Optional[Any] = 0 lowerCAmelCase : Any = 0 lowerCAmelCase : int = 0 lowerCAmelCase : int = 0 # compute the shape of the output matrix lowerCAmelCase : str = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape lowerCAmelCase : Dict = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix lowerCAmelCase : Optional[int] = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 lowerCAmelCase : str = 0 lowerCAmelCase : List[Any] = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image snake_case__ : Optional[Any] = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
314
0
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowercase_ (nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : float = 0.0 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : bool = True SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = [] __lowercase = [] for i in range(self.num_layers ): __lowercase = self.in_channels if i == 0 else self.out_channels __lowercase = FlaxResnetBlockaD( in_channels=lowercase__ ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(lowercase__ ) __lowercase = FlaxTransformeraDModel( in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(lowercase__ ) __lowercase = resnets __lowercase = attentions if self.add_downsample: __lowercase = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : str ,lowercase__ : Optional[int] ,lowercase__ : Optional[Any] ,lowercase__ : List[Any] ,lowercase__ : int=True ): __lowercase = () for resnet, attn in zip(self.resnets ,self.attentions ): __lowercase = resnet(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) __lowercase = attn(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) output_states += (hidden_states,) if self.add_downsample: __lowercase = self.downsamplers_a(lowercase__ ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ (nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : float = 0.0 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : bool = True SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = [] for i in range(self.num_layers ): __lowercase = self.in_channels if i == 0 else self.out_channels __lowercase = FlaxResnetBlockaD( in_channels=lowercase__ ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(lowercase__ ) __lowercase = resnets if self.add_downsample: __lowercase = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : Union[str, Any] ,lowercase__ : Any ,lowercase__ : Any ,lowercase__ : Optional[int]=True ): __lowercase = () for resnet in self.resnets: __lowercase = resnet(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) output_states += (hidden_states,) if self.add_downsample: __lowercase = self.downsamplers_a(lowercase__ ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ (nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : float = 0.0 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : bool = True SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase = [] __lowercase = [] for i in range(self.num_layers ): __lowercase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __lowercase = self.prev_output_channel if i == 0 else self.out_channels __lowercase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(lowercase__ ) __lowercase = FlaxTransformeraDModel( in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(lowercase__ ) __lowercase = resnets __lowercase = attentions if self.add_upsample: __lowercase = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : Tuple ,lowercase__ : Optional[int] ,lowercase__ : int ,lowercase__ : str ,lowercase__ : str ,lowercase__ : int=True ): for resnet, attn in zip(self.resnets ,self.attentions ): # pop res hidden states __lowercase = res_hidden_states_tuple[-1] __lowercase = res_hidden_states_tuple[:-1] __lowercase = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 ) __lowercase = resnet(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) __lowercase = attn(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) if self.add_upsample: __lowercase = self.upsamplers_a(lowercase__ ) return hidden_states class lowercase_ (nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : float = 0.0 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : bool = True SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = [] for i in range(self.num_layers ): __lowercase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __lowercase = self.prev_output_channel if i == 0 else self.out_channels __lowercase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(lowercase__ ) __lowercase = resnets if self.add_upsample: __lowercase = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : List[Any] ,lowercase__ : Any ,lowercase__ : List[str] ,lowercase__ : Optional[Any] ,lowercase__ : Any=True ): for resnet in self.resnets: # pop res hidden states __lowercase = res_hidden_states_tuple[-1] __lowercase = res_hidden_states_tuple[:-1] __lowercase = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 ) __lowercase = resnet(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) if self.add_upsample: __lowercase = self.upsamplers_a(lowercase__ ) return hidden_states class lowercase_ (nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : float = 0.0 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : bool = False SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Tuple ): # there is always at least one resnet __lowercase = [ FlaxResnetBlockaD( in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) ] __lowercase = [] for _ in range(self.num_layers ): __lowercase = FlaxTransformeraDModel( in_channels=self.in_channels ,n_heads=self.num_attention_heads ,d_head=self.in_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(lowercase__ ) __lowercase = FlaxResnetBlockaD( in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(lowercase__ ) __lowercase = resnets __lowercase = attentions def __call__( self : Union[str, Any] ,lowercase__ : str ,lowercase__ : str ,lowercase__ : List[str] ,lowercase__ : Optional[int]=True ): __lowercase = self.resnets[0](lowercase__ ,lowercase__ ) for attn, resnet in zip(self.attentions ,self.resnets[1:] ): __lowercase = attn(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) __lowercase = resnet(lowercase__ ,lowercase__ ,deterministic=lowercase__ ) return hidden_states
104
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''encoder.layer_norm_for_extract''': '''layer_norm_for_extract''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''label_embs_concat''': '''label_embeddings_concat''', '''mask_emb''': '''masked_spec_embed''', '''spk_proj''': '''speaker_proj''', } lowerCAmelCase__ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', '''label_embeddings_concat''', '''speaker_proj''', '''layer_norm_for_extract''', ] def _A ( A__ , A__ , A__ , A__ , A__ ): """simple docstring""" for attribute in key.split('''.''' ): __lowercase = getattr(A__ , A__ ) if weight_type is not None: __lowercase = getattr(A__ , A__ ).shape else: __lowercase = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowercase = value elif weight_type == "weight_g": __lowercase = value elif weight_type == "weight_v": __lowercase = value elif weight_type == "bias": __lowercase = value else: __lowercase = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _A ( A__ , A__ ): """simple docstring""" __lowercase = [] __lowercase = fairseq_model.state_dict() __lowercase = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __lowercase = False if "conv_layers" in name: load_conv_layer( A__ , A__ , A__ , A__ , hf_model.config.feat_extract_norm == '''group''' , ) __lowercase = True else: for key, mapped_key in MAPPING.items(): __lowercase = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue __lowercase = True if "*" in mapped_key: __lowercase = name.split(A__ )[0].split('''.''' )[-2] __lowercase = mapped_key.replace('''*''' , A__ ) if "weight_g" in name: __lowercase = '''weight_g''' elif "weight_v" in name: __lowercase = '''weight_v''' elif "bias" in name: __lowercase = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowercase = '''weight''' else: __lowercase = None set_recursively(A__ , A__ , A__ , A__ , A__ ) continue if not is_used: unused_weights.append(A__ ) logger.warning(F"Unused weights: {unused_weights}" ) def _A ( A__ , A__ , A__ , A__ , A__ ): """simple docstring""" __lowercase = full_name.split('''conv_layers.''' )[-1] __lowercase = name.split('''.''' ) __lowercase = int(items[0] ) __lowercase = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowercase = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowercase = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found." ) __lowercase = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowercase = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(A__ ) @torch.no_grad() def _A ( A__ , A__ , A__=None , A__=None , A__=True ): """simple docstring""" if config_path is not None: __lowercase = UniSpeechSatConfig.from_pretrained(A__ ) else: __lowercase = UniSpeechSatConfig() __lowercase = '''''' if is_finetuned: __lowercase = UniSpeechSatForCTC(A__ ) else: __lowercase = UniSpeechSatForPreTraining(A__ ) __lowercase , __lowercase , __lowercase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) __lowercase = model[0].eval() recursively_load_weights(A__ , A__ ) hf_wavavec.save_pretrained(A__ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) lowerCAmelCase__ = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
104
1
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": lowerCAmelCase__ :Dict = pd.read_csv('''sample_data.csv''', header=None) lowerCAmelCase__ :int = df.shape[:1][0] # If you're using some other dataset input the target column lowerCAmelCase__ :Union[str, Any] = df.iloc[:, 1:2] lowerCAmelCase__ :Optional[int] = actual_data.values.reshape(len_data, 1) lowerCAmelCase__ :Tuple = MinMaxScaler().fit_transform(actual_data) lowerCAmelCase__ :str = 1_0 lowerCAmelCase__ :Optional[Any] = 5 lowerCAmelCase__ :List[str] = 2_0 lowerCAmelCase__ :Any = len_data - periods * look_back lowerCAmelCase__ :Union[str, Any] = actual_data[:division] lowerCAmelCase__ :Tuple = actual_data[division - look_back :] lowerCAmelCase__ :Optional[int] = [], [] lowerCAmelCase__ :str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) lowerCAmelCase__ :Optional[Any] = np.array(train_x) lowerCAmelCase__ :Any = np.array(test_x) lowerCAmelCase__ :Dict = np.array([list(i.ravel()) for i in train_y]) lowerCAmelCase__ :Tuple = np.array([list(i.ravel()) for i in test_y]) lowerCAmelCase__ :Optional[int] = Sequential() model.add(LSTM(1_2_8, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(6_4, input_shape=(1_2_8, 1))) model.add(Dense(forward_days)) model.compile(loss='''mean_squared_error''', optimizer='''adam''') lowerCAmelCase__ :List[Any] = model.fit( x_train, y_train, epochs=1_5_0, verbose=1, shuffle=True, batch_size=4 ) lowerCAmelCase__ :Optional[Any] = model.predict(x_test)
368
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[Any]: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Tuple = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = ConditionalDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
185
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE_: Dict ={ 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[Any] =[ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: List[Any] =[ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : list , snake_case_ : int | None = None , snake_case_ : int | None = None ) -> None: '''simple docstring''' if start is None: UpperCAmelCase_ = 0 if end is None: UpperCAmelCase_ = len(snake_case_ ) - 1 if start >= end: return UpperCAmelCase_ = (start + end) // 2 slowsort(snake_case_ , snake_case_ , snake_case_ ) slowsort(snake_case_ , mid + 1 , snake_case_ ) if sequence[end] < sequence[mid]: UpperCAmelCase_ , UpperCAmelCase_ = sequence[mid], sequence[end] slowsort(snake_case_ , snake_case_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
1
1
from __future__ import annotations from math import pow, sqrt def lowercase ( _snake_case : float , _snake_case : float , _snake_case : float ) ->List[str]: """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance == 0: return {"resistance": sqrt(pow(_snake_case , 2 ) - pow(_snake_case , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_snake_case , 2 ) - pow(_snake_case , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_snake_case , 2 ) + pow(_snake_case , 2 ) )} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
355
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class _UpperCAmelCase : '''simple docstring''' def __init__(self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=24 , a_=2 , a_=6 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=5_12 , a_=16 , a_=2 , a_=0.02 , a_=3 , a_=None , a_=10_00 , ): '''simple docstring''' __snake_case : Any = parent __snake_case : int = batch_size __snake_case : Dict = seq_length __snake_case : List[str] = is_training __snake_case : List[Any] = use_input_mask __snake_case : int = use_token_type_ids __snake_case : Union[str, Any] = use_labels __snake_case : str = vocab_size __snake_case : int = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : int = num_attention_heads __snake_case : str = intermediate_size __snake_case : Union[str, Any] = hidden_act __snake_case : int = hidden_dropout_prob __snake_case : Union[str, Any] = attention_probs_dropout_prob __snake_case : List[Any] = max_position_embeddings __snake_case : Any = type_vocab_size __snake_case : Dict = type_sequence_label_size __snake_case : Optional[Any] = initializer_range __snake_case : Union[str, Any] = num_labels __snake_case : Any = scope __snake_case : Any = range_bbox def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : int = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # 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]: __snake_case : List[str] = bbox[i, j, 3] __snake_case : Any = bbox[i, j, 1] __snake_case : Tuple = t if bbox[i, j, 2] < bbox[i, j, 0]: __snake_case : List[str] = bbox[i, j, 2] __snake_case : Union[str, Any] = bbox[i, j, 0] __snake_case : Dict = t __snake_case : Optional[int] = None if self.use_input_mask: __snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __snake_case : Dict = None if self.use_token_type_ids: __snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : List[str] = None __snake_case : Union[str, Any] = None if self.use_labels: __snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : List[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return LiltConfig( 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 , ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): '''simple docstring''' __snake_case : Union[str, Any] = LiltModel(config=a_ ) model.to(a_ ) model.eval() __snake_case : Any = model(a_ , bbox=a_ , attention_mask=a_ , token_type_ids=a_ ) __snake_case : str = model(a_ , bbox=a_ , token_type_ids=a_ ) __snake_case : List[str] = model(a_ , bbox=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 SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): '''simple docstring''' __snake_case : Optional[int] = self.num_labels __snake_case : List[str] = LiltForTokenClassification(config=a_ ) model.to(a_ ) model.eval() __snake_case : Tuple = model( a_ , bbox=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 SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): '''simple docstring''' __snake_case : Optional[Any] = LiltForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() __snake_case : int = model( a_ , bbox=a_ , attention_mask=a_ , token_type_ids=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 SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : Dict = config_and_inputs __snake_case : Any = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class _UpperCAmelCase ( __snake_case, __snake_case, __snake_case, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase__ =( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ =False lowerCamelCase__ =False def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_ , a_ ): '''simple docstring''' return True def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Union[str, Any] = LiltModelTester(self ) __snake_case : Optional[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __snake_case : Dict = type self.model_tester.create_and_check_model(*a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Any = LiltModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch @slow class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Union[str, Any] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(a_ ) __snake_case : Dict = torch.tensor([[1, 2]] , device=a_ ) __snake_case : str = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=a_ ) # forward pass with torch.no_grad(): __snake_case : Union[str, Any] = model(input_ids=a_ , bbox=a_ ) __snake_case : Union[str, Any] = torch.Size([1, 2, 7_68] ) __snake_case : str = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=a_ , ) self.assertTrue(outputs.last_hidden_state.shape , a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , a_ , atol=1E-3 ) )
24
0
"""simple docstring""" import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def _snake_case ( lowercase__ : Union[str, Any] , lowercase__ : Optional[int] , lowercase__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ :Dict = os.path.abspath(lowercase__ ) logger.info(f"""Converting TensorFlow checkpoint from {tf_path}""" ) # Load weights from TF model lowerCAmelCase_ :Any = tf.train.list_variables(lowercase__ ) lowerCAmelCase_ :List[str] = [] lowerCAmelCase_ :str = [] lowerCAmelCase_ :int = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") lowerCAmelCase_ :Union[str, Any] = full_name.split("""/""" ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f"""Skipping non-model layer {full_name}""" ) continue if "optimizer" in full_name: logger.info(f"""Skipping optimization layer {full_name}""" ) continue if name[0] == "model": # ignore initial 'model' lowerCAmelCase_ :Dict = name[1:] # figure out how many levels deep the name is lowerCAmelCase_ :Tuple = 0 for _name in name: if _name.startswith("""layer_with_weights""" ): depth += 1 else: break layer_depth.append(lowercase__ ) # read data lowerCAmelCase_ :Optional[Any] = tf.train.load_variable(lowercase__ , lowercase__ ) names.append("""/""".join(lowercase__ ) ) arrays.append(lowercase__ ) logger.info(f"""Read a total of {len(lowercase__ ):,} layers""" ) # Sanity check if len(set(lowercase__ ) ) != 1: raise ValueError(f"""Found layer names with different depths (layer depth {list(set(lowercase__ ) )})""" ) lowerCAmelCase_ :Dict = list(set(lowercase__ ) )[0] if layer_depth != 1: raise ValueError( """The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP""" """ heads.""" ) # convert layers logger.info("""Converting weights...""" ) for full_name, array in zip(lowercase__ , lowercase__ ): lowerCAmelCase_ :str = full_name.split("""/""" ) lowerCAmelCase_ :Union[str, Any] = model lowerCAmelCase_ :Tuple = [] for i, m_name in enumerate(lowercase__ ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith("""layer_with_weights""" ): lowerCAmelCase_ :Dict = int(m_name.split("""-""" )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(["""embeddings""", """LayerNorm"""] ) lowerCAmelCase_ :Dict = getattr(lowercase__ , """embeddings""" ) lowerCAmelCase_ :List[str] = getattr(lowercase__ , """LayerNorm""" ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(["""encoder""", """layer""", str(layer_num - 4 )] ) lowerCAmelCase_ :Optional[Any] = getattr(lowercase__ , """encoder""" ) lowerCAmelCase_ :List[str] = getattr(lowercase__ , """layer""" ) lowerCAmelCase_ :Tuple = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(["""pooler""", """dense"""] ) lowerCAmelCase_ :Tuple = getattr(lowercase__ , """pooler""" ) lowerCAmelCase_ :List[Any] = getattr(lowercase__ , """dense""" ) elif m_name == "embeddings": trace.append("""embeddings""" ) lowerCAmelCase_ :Dict = getattr(lowercase__ , """embeddings""" ) if layer_num == 0: trace.append("""word_embeddings""" ) lowerCAmelCase_ :Any = getattr(lowercase__ , """word_embeddings""" ) elif layer_num == 1: trace.append("""position_embeddings""" ) lowerCAmelCase_ :int = getattr(lowercase__ , """position_embeddings""" ) elif layer_num == 2: trace.append("""token_type_embeddings""" ) lowerCAmelCase_ :str = getattr(lowercase__ , """token_type_embeddings""" ) else: raise ValueError(f"""Unknown embedding layer with name {full_name}""" ) trace.append("""weight""" ) lowerCAmelCase_ :Tuple = getattr(lowercase__ , """weight""" ) elif m_name == "_attention_layer": # self-attention layer trace.extend(["""attention""", """self"""] ) lowerCAmelCase_ :str = getattr(lowercase__ , """attention""" ) lowerCAmelCase_ :Optional[int] = getattr(lowercase__ , """self""" ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(["""attention""", """output""", """LayerNorm"""] ) lowerCAmelCase_ :str = getattr(lowercase__ , """attention""" ) lowerCAmelCase_ :Any = getattr(lowercase__ , """output""" ) lowerCAmelCase_ :str = getattr(lowercase__ , """LayerNorm""" ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(["""attention""", """output""", """dense"""] ) lowerCAmelCase_ :Any = getattr(lowercase__ , """attention""" ) lowerCAmelCase_ :List[Any] = getattr(lowercase__ , """output""" ) lowerCAmelCase_ :List[Any] = getattr(lowercase__ , """dense""" ) elif m_name == "_output_dense": # output dense trace.extend(["""output""", """dense"""] ) lowerCAmelCase_ :Any = getattr(lowercase__ , """output""" ) lowerCAmelCase_ :Optional[int] = getattr(lowercase__ , """dense""" ) elif m_name == "_output_layer_norm": # output dense trace.extend(["""output""", """LayerNorm"""] ) lowerCAmelCase_ :Optional[int] = getattr(lowercase__ , """output""" ) lowerCAmelCase_ :Any = getattr(lowercase__ , """LayerNorm""" ) elif m_name == "_key_dense": # attention key trace.append("""key""" ) lowerCAmelCase_ :Union[str, Any] = getattr(lowercase__ , """key""" ) elif m_name == "_query_dense": # attention query trace.append("""query""" ) lowerCAmelCase_ :Union[str, Any] = getattr(lowercase__ , """query""" ) elif m_name == "_value_dense": # attention value trace.append("""value""" ) lowerCAmelCase_ :List[str] = getattr(lowercase__ , """value""" ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(["""intermediate""", """dense"""] ) lowerCAmelCase_ :Optional[Any] = getattr(lowercase__ , """intermediate""" ) lowerCAmelCase_ :Optional[int] = getattr(lowercase__ , """dense""" ) elif m_name == "_output_layer_norm": # output layer norm trace.append("""output""" ) lowerCAmelCase_ :str = getattr(lowercase__ , """output""" ) # weights & biases elif m_name in ["bias", "beta"]: trace.append("""bias""" ) lowerCAmelCase_ :Union[str, Any] = getattr(lowercase__ , """bias""" ) elif m_name in ["kernel", "gamma"]: trace.append("""weight""" ) lowerCAmelCase_ :str = getattr(lowercase__ , """weight""" ) else: logger.warning(f"""Ignored {m_name}""" ) # for certain layers reshape is necessary lowerCAmelCase_ :Dict = """.""".join(lowercase__ ) if re.match(r"""(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)""" , lowercase__ ) or re.match( r"""(\S+)\.attention\.output\.dense\.weight""" , lowercase__ ): lowerCAmelCase_ :Tuple = array.reshape(pointer.data.shape ) if "kernel" in full_name: lowerCAmelCase_ :Optional[Any] = array.transpose() if pointer.shape == array.shape: lowerCAmelCase_ :List[str] = torch.from_numpy(lowercase__ ) else: raise ValueError( f"""Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:""" f""" {array.shape}""" ) logger.info(f"""Successfully set variable {full_name} to PyTorch layer {trace}""" ) return model def _snake_case ( lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] ) -> List[str]: '''simple docstring''' logger.info(f"""Loading model based on config from {config_path}...""" ) lowerCAmelCase_ :Optional[int] = BertConfig.from_json_file(lowercase__ ) lowerCAmelCase_ :Optional[Any] = BertModel(lowercase__ ) # Load weights from checkpoint logger.info(f"""Loading weights from checkpoint {tf_checkpoint_path}...""" ) load_tfa_weights_in_bert(lowercase__ , lowercase__ , lowercase__ ) # Save pytorch-model logger.info(f"""Saving PyTorch model to {pytorch_dump_path}...""" ) torch.save(model.state_dict() , lowercase__ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow 2.x 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 (must include filename).', ) __UpperCAmelCase = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
84
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =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(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_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(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
0
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging lowerCamelCase__ = '''\ ''' lowerCamelCase__ = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' lowerCamelCase__ = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ (datasets.Metric ): def __a ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "input_texts": datasets.Value("string" ), } ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , ) def __a ( self , _a , _a , _a = 16 , _a = True , _a=None ) -> Any: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": lowerCAmelCase_ = "cuda" else: lowerCAmelCase_ = "cuda" if torch.cuda.is_available() else "cpu" lowerCAmelCase_ = AutoModelForCausalLM.from_pretrained(_a ) lowerCAmelCase_ = model.to(_a ) lowerCAmelCase_ = AutoTokenizer.from_pretrained(_a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: lowerCAmelCase_ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" lowerCAmelCase_ = model.config.max_length - 1 else: lowerCAmelCase_ = model.config.max_length lowerCAmelCase_ = tokenizer( _a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , return_tensors="pt" , return_attention_mask=_a , ).to(_a ) lowerCAmelCase_ = encodings["input_ids"] lowerCAmelCase_ = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." lowerCAmelCase_ = [] lowerCAmelCase_ = CrossEntropyLoss(reduction="none" ) for start_index in logging.tqdm(range(0 , len(_a ) , _a ) ): lowerCAmelCase_ = min(start_index + batch_size , len(_a ) ) lowerCAmelCase_ = encoded_texts[start_index:end_index] lowerCAmelCase_ = attn_masks[start_index:end_index] if add_start_token: lowerCAmelCase_ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_a ) lowerCAmelCase_ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) lowerCAmelCase_ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_a ), attn_mask] , dim=1 ) lowerCAmelCase_ = encoded_batch with torch.no_grad(): lowerCAmelCase_ = model(_a , attention_mask=_a ).logits lowerCAmelCase_ = out_logits[..., :-1, :].contiguous() lowerCAmelCase_ = labels[..., 1:].contiguous() lowerCAmelCase_ = attn_mask[..., 1:].contiguous() lowerCAmelCase_ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_a )}
357
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def A(__a: Any , __a: Union[str, Any] , __a: List[str] ): lowerCAmelCase_ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] lowerCAmelCase_ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } lowerCAmelCase_ = F"{src_lang}-{tgt_lang}" lowerCAmelCase_ = F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(__a , exist_ok=__a ) lowerCAmelCase_ = os.path.join(__a , "README.md" ) print(F"Generating {path}" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(__a ) # make sure we are under the root of the project lowerCamelCase__ = Path(__file__).resolve().parent.parent.parent lowerCamelCase__ = repo_dir / '''model_cards''' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = model_name.split('''-''') lowerCamelCase__ = model_cards_dir / '''facebook''' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
22
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer lowerCAmelCase__ : Tuple = logging.get_logger(__name__) lowerCAmelCase__ : Tuple = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase__ : Tuple = { 'vocab_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt', }, 'tokenizer_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json' ), 'google/realm-orqa-nq-openqa': ( 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-nq-reader': ( 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-openqa': ( 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-reader': ( 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json' ), }, } lowerCAmelCase__ : int = { 'google/realm-cc-news-pretrained-embedder': 512, 'google/realm-cc-news-pretrained-encoder': 512, 'google/realm-cc-news-pretrained-scorer': 512, 'google/realm-cc-news-pretrained-openqa': 512, 'google/realm-orqa-nq-openqa': 512, 'google/realm-orqa-nq-reader': 512, 'google/realm-orqa-wq-openqa': 512, 'google/realm-orqa-wq-reader': 512, } lowerCAmelCase__ : Optional[int] = { 'google/realm-cc-news-pretrained-embedder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-encoder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-scorer': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-reader': {'do_lower_case': True}, 'google/realm-orqa-wq-openqa': {'do_lower_case': True}, 'google/realm-orqa-wq-reader': {'do_lower_case': True}, } class snake_case ( __lowerCamelCase ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_INIT_CONFIGURATION snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = RealmTokenizer def __init__( self : int ,lowerCamelCase__ : Tuple=None ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : Any="[UNK]" ,lowerCamelCase__ : List[Any]="[SEP]" ,lowerCamelCase__ : Tuple="[PAD]" ,lowerCamelCase__ : Dict="[CLS]" ,lowerCamelCase__ : Optional[int]="[MASK]" ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : str=None ,**lowerCamelCase__ : Any ,): super().__init__( UpperCamelCase_ ,tokenizer_file=UpperCamelCase_ ,do_lower_case=UpperCamelCase_ ,unk_token=UpperCamelCase_ ,sep_token=UpperCamelCase_ ,pad_token=UpperCamelCase_ ,cls_token=UpperCamelCase_ ,mask_token=UpperCamelCase_ ,tokenize_chinese_chars=UpperCamelCase_ ,strip_accents=UpperCamelCase_ ,**UpperCamelCase_ ,) UpperCAmelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' ,UpperCamelCase_ ) != do_lower_case or normalizer_state.get('strip_accents' ,UpperCamelCase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' ,UpperCamelCase_ ) != tokenize_chinese_chars ): UpperCAmelCase__ = getattr(UpperCamelCase_ ,normalizer_state.pop('type' ) ) UpperCAmelCase__ = do_lower_case UpperCAmelCase__ = strip_accents UpperCAmelCase__ = tokenize_chinese_chars UpperCAmelCase__ = normalizer_class(**UpperCamelCase_ ) UpperCAmelCase__ = do_lower_case def __lowerCAmelCase ( self : Optional[Any] ,lowerCamelCase__ : int ,**lowerCamelCase__ : Union[str, Any] ): UpperCAmelCase__ = PaddingStrategy.MAX_LENGTH UpperCAmelCase__ = text UpperCAmelCase__ = kwargs.pop('text_pair' ,UpperCamelCase_ ) UpperCAmelCase__ = kwargs.pop('return_tensors' ,UpperCamelCase_ ) UpperCAmelCase__ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(UpperCamelCase_ ): if batch_text_pair is not None: UpperCAmelCase__ = batch_text_pair[idx] else: UpperCAmelCase__ = None UpperCAmelCase__ = super().__call__(UpperCamelCase_ ,UpperCamelCase_ ,return_tensors=UpperCamelCase_ ,**UpperCamelCase_ ) UpperCAmelCase__ = encoded_candidates.get('input_ids' ) UpperCAmelCase__ = encoded_candidates.get('attention_mask' ) UpperCAmelCase__ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(UpperCamelCase_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(UpperCamelCase_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(UpperCamelCase_ ) UpperCAmelCase__ = {key: item for key, item in output_data.items() if len(UpperCamelCase_ ) != 0} return BatchEncoding(UpperCamelCase_ ,tensor_type=UpperCamelCase_ ) def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any]=None ): UpperCAmelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Union[str, Any] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ): UpperCAmelCase__ = [self.sep_token_id] UpperCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Union[str, Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[str] = None ): UpperCAmelCase__ = self._tokenizer.model.save(UpperCamelCase_ ,name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
98
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate UpperCAmelCase_ = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) UpperCAmelCase_ = [] UpperCAmelCase_ = [] UpperCAmelCase_ = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} UpperCAmelCase_ = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': f"""🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results""", 'emoji': True, }, } ] UpperCAmelCase_ = 0 for log in Path().glob('*.log'): UpperCAmelCase_ = 0 with open(log, 'r') as f: for line in f: UpperCAmelCase_ = json.loads(line) if line.get('nodeid', '') != "": UpperCAmelCase_ = line['nodeid'] if line.get('duration', None) is not None: UpperCAmelCase_ = f"""{line["duration"]:.4f}""" if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) UpperCAmelCase_ = [] log.unlink() UpperCAmelCase_ = '' UpperCAmelCase_ = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" UpperCAmelCase_ = [] UpperCAmelCase_ = {} for test in failed_tests: UpperCAmelCase_ = test[0].split('::') UpperCAmelCase_ = data[0].split('/')[-1] if data[0] not in filesafailed: UpperCAmelCase_ = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) UpperCAmelCase_ = [test[0] for test in failed_table] UpperCAmelCase_ = list(set(files)) # Count number of instances in failed_tests UpperCAmelCase_ = [] for file in individual_files: table.append([file, len(filesafailed[file])]) UpperCAmelCase_ = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3_000: UpperCAmelCase_ = 'Too many failed tests, please see the full report in the Action results.' UpperCAmelCase_ = len(err) + 10 UpperCAmelCase_ = message[: 3_000 - offset] + f"""\n...\n```\n{err}""" print(f"""### {message}""") else: UpperCAmelCase_ = 'No failed tests! 🤗' print(f"""## {message}""") payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient UpperCAmelCase_ = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": UpperCAmelCase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) UpperCAmelCase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': f"""https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } payload.append(action_button) UpperCAmelCase_ = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': f"""Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}""", } ], } payload.append(date_report) UpperCAmelCase_ = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) UpperCAmelCase_ = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name UpperCAmelCase_ = '' for i, row in enumerate(test_failures): if row[0] != test_class: UpperCAmelCase_ = row[0] else: UpperCAmelCase_ = '' UpperCAmelCase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': f"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```""", }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
12
0
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A_ : '''simple docstring''' def __init__( self : str , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : Optional[Any]=7 , lowercase_ : int=False , lowercase_ : Tuple=True , lowercase_ : str=False , lowercase_ : List[Any]=True , lowercase_ : int=33 , lowercase_ : Optional[int]=32 , lowercase_ : Union[str, Any]=5 , lowercase_ : Union[str, Any]=4 , lowercase_ : Any=37 , lowercase_ : Any="gelu" , lowercase_ : Optional[Any]=0.1 , lowercase_ : Optional[int]=0.1 , lowercase_ : Tuple=512 , lowercase_ : Any=16 , lowercase_ : List[str]=2 , lowercase_ : Optional[int]=0.02 , lowercase_ : Optional[int]=3 , lowercase_ : Dict=4 , lowercase_ : Optional[int]=None , ) -> Dict: UpperCAmelCase : Dict = parent UpperCAmelCase : List[Any] = batch_size UpperCAmelCase : Tuple = seq_length UpperCAmelCase : Optional[Any] = is_training UpperCAmelCase : str = use_input_mask UpperCAmelCase : Optional[int] = use_token_type_ids UpperCAmelCase : List[str] = use_labels UpperCAmelCase : Union[str, Any] = vocab_size UpperCAmelCase : List[Any] = hidden_size UpperCAmelCase : Optional[Any] = num_hidden_layers UpperCAmelCase : Dict = num_attention_heads UpperCAmelCase : Dict = intermediate_size UpperCAmelCase : List[Any] = hidden_act UpperCAmelCase : str = hidden_dropout_prob UpperCAmelCase : str = attention_probs_dropout_prob UpperCAmelCase : Dict = max_position_embeddings UpperCAmelCase : Optional[int] = type_vocab_size UpperCAmelCase : Optional[int] = type_sequence_label_size UpperCAmelCase : List[Any] = initializer_range UpperCAmelCase : Union[str, Any] = num_labels UpperCAmelCase : int = num_choices UpperCAmelCase : Union[str, Any] = scope def UpperCAmelCase_ ( self : Dict ) -> List[Any]: UpperCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase : Optional[Any] = None UpperCAmelCase : List[Any] = None UpperCAmelCase : Any = None if self.use_labels: UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase : str = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : str ) -> Tuple: return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCAmelCase_ ( self : List[Any] , lowercase_ : int , lowercase_ : Tuple , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Any ) -> str: UpperCAmelCase : str = EsmModel(config=__A ) model.to(__A ) model.eval() UpperCAmelCase : Dict = model(__A , attention_mask=__A ) UpperCAmelCase : Any = model(__A ) UpperCAmelCase : List[Any] = 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 : List[Any] , lowercase_ : Any , lowercase_ : str , lowercase_ : Any , lowercase_ : str , lowercase_ : List[Any] , lowercase_ : Any ) -> List[str]: UpperCAmelCase : List[Any] = EsmForMaskedLM(config=__A ) model.to(__A ) model.eval() UpperCAmelCase : Optional[int] = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : str , lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : Union[str, Any] ) -> int: UpperCAmelCase : List[Any] = self.num_labels UpperCAmelCase : Optional[int] = EsmForTokenClassification(config=__A ) model.to(__A ) model.eval() UpperCAmelCase : Dict = 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 : Optional[int] ) -> List[Any]: UpperCAmelCase : Any = self.prepare_config_and_inputs() ( UpperCAmelCase ) : Optional[int] = config_and_inputs UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A_ ( A__ , A__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : Dict = False UpperCAmelCase_ : List[Any] = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) UpperCAmelCase_ : Union[str, Any] = () UpperCAmelCase_ : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase_ : Any = True def UpperCAmelCase_ ( self : int ) -> str: UpperCAmelCase : Any = EsmModelTester(self ) UpperCAmelCase : List[str] = ConfigTester(self , config_class=__A , hidden_size=37 ) def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : str ) -> str: UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def UpperCAmelCase_ ( self : List[str] ) -> Dict: UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase : List[Any] = type self.model_tester.create_and_check_model(*__A ) def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__A ) def UpperCAmelCase_ ( self : str ) -> Any: UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) @slow def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase : Any = EsmModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs()[0] UpperCAmelCase : Dict = EsmEmbeddings(config=__A ) UpperCAmelCase : Optional[Any] = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) UpperCAmelCase : str = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) UpperCAmelCase : List[Any] = create_position_ids_from_input_ids(__A , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__A , __A ) ) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs()[0] UpperCAmelCase : List[str] = EsmEmbeddings(config=__A ) UpperCAmelCase : int = torch.empty(2 , 4 , 30 ) UpperCAmelCase : Tuple = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] UpperCAmelCase : Dict = torch.as_tensor([expected_single_positions, expected_single_positions] ) UpperCAmelCase : List[str] = embeddings.create_position_ids_from_inputs_embeds(__A ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__A , __A ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCAmelCase_ ( self : Dict ) -> Dict: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCAmelCase_ ( self : List[Any] ) -> str: pass @require_torch class A_ ( A__ ): '''simple docstring''' @slow def UpperCAmelCase_ ( self : Tuple ) -> List[str]: with torch.no_grad(): UpperCAmelCase : int = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() UpperCAmelCase : List[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase : Optional[int] = model(__A )[0] UpperCAmelCase : Optional[Any] = 33 UpperCAmelCase : Union[str, Any] = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , __A ) UpperCAmelCase : List[str] = torch.tensor( [[[8.9215, -10.5_898, -6.4671], [-6.3967, -13.9_114, -1.1212], [-7.7812, -13.9_516, -3.7406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : List[str] ) -> List[str]: with torch.no_grad(): UpperCAmelCase : Any = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() UpperCAmelCase : Dict = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) UpperCAmelCase : Union[str, Any] = model(__A )[0] # compare the actual values for a slice. UpperCAmelCase : List[str] = torch.tensor( [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) )
351
'''simple docstring''' def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): UpperCAmelCase : int = len(UpperCAmelCase_ ) UpperCAmelCase : int = len(UpperCAmelCase_ ) UpperCAmelCase : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) UpperCAmelCase : list = [] for char_count in range(UpperCAmelCase_ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(UpperCAmelCase_ ) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
280
0
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase__ =random.Random() def __UpperCamelCase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any]=1.0 , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Optional[Any]=None ): if rng is None: __a : Dict = global_rng __a : int = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): def __init__(self : str , snake_case_ : Tuple , snake_case_ : Optional[Any]=7 , snake_case_ : int=4_0_0 , snake_case_ : Dict=2_0_0_0 , snake_case_ : Tuple=1 , snake_case_ : Union[str, Any]=0.0 , snake_case_ : List[Any]=1_6_0_0_0 , snake_case_ : int=True , snake_case_ : Union[str, Any]=True , ): __a : List[Any] = parent __a : Dict = batch_size __a : str = min_seq_length __a : Any = max_seq_length __a : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __a : int = feature_size __a : Tuple = padding_value __a : Union[str, Any] = sampling_rate __a : List[str] = return_attention_mask __a : Tuple = do_normalize def lowerCAmelCase (self : str ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCAmelCase (self : Optional[Any] , snake_case_ : Any=False , snake_case_ : Optional[Any]=False ): def _flatten(snake_case_ : Optional[Any] ): return list(itertools.chain(*snake_case_ ) ) if equal_length: __a : int = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __a : str = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __a : List[str] = [np.asarray(snake_case_ ) for x in speech_inputs] return speech_inputs class UpperCamelCase__ ( __lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = WavaVecaFeatureExtractor def lowerCAmelCase (self : List[Any] ): __a : Dict = WavaVecaFeatureExtractionTester(self ) def lowerCAmelCase (self : Optional[int] , snake_case_ : Any ): self.assertTrue(np.all(np.mean(snake_case_ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case_ , axis=0 ) - 1 ) < 1E-3 ) ) def lowerCAmelCase (self : Tuple ): # Tests that all call wrap to encode_plus and batch_encode_plus __a : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __a : Union[str, Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __a : Union[str, Any] = [np.asarray(snake_case_ ) for speech_input in speech_inputs] # Test not batched input __a : int = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values __a : Any = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1E-3 ) ) # Test batched __a : Optional[int] = feat_extract(snake_case_ , return_tensors='''np''' ).input_values __a : Optional[Any] = feat_extract(snake_case_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(snake_case_ , snake_case_ ): self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __a : Any = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] __a : Optional[int] = np.asarray(snake_case_ ) __a : str = feat_extract(snake_case_ , return_tensors='''np''' ).input_values __a : List[str] = feat_extract(snake_case_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(snake_case_ , snake_case_ ): self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1E-3 ) ) def lowerCAmelCase (self : Optional[Any] ): __a : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __a : Tuple = ['''longest''', '''max_length''', '''do_not_pad'''] __a : Union[str, Any] = [None, 1_6_0_0, None] for max_length, padding in zip(snake_case_ , snake_case_ ): __a : int = feat_extract(snake_case_ , padding=snake_case_ , max_length=snake_case_ , return_tensors='''np''' ) __a : List[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def lowerCAmelCase (self : Dict ): __a : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Optional[Any] = range(8_0_0 , 1_4_0_0 , 2_0_0 ) __a : Optional[int] = [floats_list((1, x) )[0] for x in lengths] __a : str = ['''longest''', '''max_length''', '''do_not_pad'''] __a : Optional[Any] = [None, 1_6_0_0, None] for max_length, padding in zip(snake_case_ , snake_case_ ): __a : List[str] = feat_extract(snake_case_ , max_length=snake_case_ , padding=snake_case_ ) __a : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def lowerCAmelCase (self : Any ): __a : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : int = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __a : str = feat_extract( snake_case_ , truncation=snake_case_ , max_length=1_0_0_0 , padding='''max_length''' , return_tensors='''np''' ) __a : List[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def lowerCAmelCase (self : List[Any] ): __a : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __a : int = feat_extract( snake_case_ , truncation=snake_case_ , max_length=1_0_0_0 , padding='''longest''' , return_tensors='''np''' ) __a : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) __a : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __a : List[Any] = feat_extract( snake_case_ , truncation=snake_case_ , max_length=2_0_0_0 , padding='''longest''' , return_tensors='''np''' ) __a : List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) @require_torch def lowerCAmelCase (self : Any ): import torch __a : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Tuple = np.random.rand(1_0_0 ).astype(np.floataa ) __a : Optional[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __a : Any = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __a : List[str] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def lowerCAmelCase (self : str ): # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: __a : int = WavaVecaConfig.from_pretrained(snake_case_ ) __a : Dict = WavaVecaFeatureExtractor.from_pretrained(snake_case_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
216
from __future__ import annotations import math import random from typing import Any class UpperCamelCase__ : def __init__(self : Optional[Any] ): __a : list[Any] = [] __a : int = 0 __a : int = 0 def lowerCAmelCase (self : Optional[int] ): return self.head == self.tail def lowerCAmelCase (self : List[Any] , snake_case_ : Any ): self.data.append(snake_case_ ) __a : str = self.tail + 1 def lowerCAmelCase (self : Optional[int] ): __a : int = self.data[self.head] __a : Union[str, Any] = self.head + 1 return ret def lowerCAmelCase (self : Union[str, Any] ): return self.tail - self.head def lowerCAmelCase (self : Union[str, Any] ): print(self.data ) print('''**************''' ) print(self.data[self.head : self.tail] ) class UpperCamelCase__ : def __init__(self : List[str] , snake_case_ : Any ): __a : List[str] = data __a : MyNode | None = None __a : MyNode | None = None __a : int = 1 def lowerCAmelCase (self : int ): return self.data def lowerCAmelCase (self : Dict ): return self.left def lowerCAmelCase (self : int ): return self.right def lowerCAmelCase (self : int ): return self.height def lowerCAmelCase (self : Optional[Any] , snake_case_ : Any ): __a : Tuple = data def lowerCAmelCase (self : Any , snake_case_ : MyNode | None ): __a : Any = node def lowerCAmelCase (self : Union[str, Any] , snake_case_ : MyNode | None ): __a : List[str] = node def lowerCAmelCase (self : Optional[int] , snake_case_ : int ): __a : Union[str, Any] = height def __UpperCamelCase ( lowerCAmelCase__ : MyNode | None ): if node is None: return 0 return node.get_height() def __UpperCamelCase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): if a > b: return a return b def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): print('''left rotation node:''' , node.get_data() ) __a : str = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowerCAmelCase__ ) __a : List[Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase__ ) __a : Union[str, Any] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase__ ) return ret def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): print('''right rotation node:''' , node.get_data() ) __a : List[Any] = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowerCAmelCase__ ) __a : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase__ ) __a : List[str] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase__ ) return ret def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): __a : Union[str, Any] = node.get_left() assert left_child is not None node.set_left(left_rotation(lowerCAmelCase__ ) ) return right_rotation(lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): __a : Optional[int] = node.get_right() assert right_child is not None node.set_right(right_rotation(lowerCAmelCase__ ) ) return left_rotation(lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : MyNode | None , lowerCAmelCase__ : Any ): if node is None: return MyNode(lowerCAmelCase__ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowerCAmelCase__ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected __a : Tuple = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child __a : str = right_rotation(lowerCAmelCase__ ) else: __a : Dict = lr_rotation(lowerCAmelCase__ ) else: node.set_right(insert_node(node.get_right() , lowerCAmelCase__ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: __a : Dict = node.get_right() assert right_child is not None if data < right_child.get_data(): __a : str = rl_rotation(lowerCAmelCase__ ) else: __a : Tuple = left_rotation(lowerCAmelCase__ ) __a : Any = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase__ ) return node def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): while True: __a : Union[str, Any] = root.get_right() if right_child is None: break __a : str = right_child return root.get_data() def __UpperCamelCase ( lowerCAmelCase__ : MyNode ): while True: __a : Optional[int] = root.get_left() if left_child is None: break __a : int = left_child return root.get_data() def __UpperCamelCase ( lowerCAmelCase__ : MyNode , lowerCAmelCase__ : Any ): __a : Optional[Any] = root.get_left() __a : List[str] = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: __a : str = get_left_most(lowerCAmelCase__ ) root.set_data(lowerCAmelCase__ ) root.set_right(del_node(lowerCAmelCase__ , lowerCAmelCase__ ) ) elif left_child is not None: __a : int = left_child elif right_child is not None: __a : List[Any] = right_child else: return None elif root.get_data() > data: if left_child is None: print('''No such data''' ) return root else: root.set_left(del_node(lowerCAmelCase__ , lowerCAmelCase__ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowerCAmelCase__ , lowerCAmelCase__ ) ) if get_height(lowerCAmelCase__ ) - get_height(lowerCAmelCase__ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): __a : List[Any] = left_rotation(lowerCAmelCase__ ) else: __a : Union[str, Any] = rl_rotation(lowerCAmelCase__ ) elif get_height(lowerCAmelCase__ ) - get_height(lowerCAmelCase__ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): __a : int = right_rotation(lowerCAmelCase__ ) else: __a : Tuple = lr_rotation(lowerCAmelCase__ ) __a : str = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowerCAmelCase__ ) return root class UpperCamelCase__ : def __init__(self : Optional[Any] ): __a : MyNode | None = None def lowerCAmelCase (self : List[Any] ): return get_height(self.root ) def lowerCAmelCase (self : Any , snake_case_ : Any ): print('''insert:''' + str(snake_case_ ) ) __a : List[Any] = insert_node(self.root , snake_case_ ) def lowerCAmelCase (self : Dict , snake_case_ : Any ): print('''delete:''' + str(snake_case_ ) ) if self.root is None: print('''Tree is empty!''' ) return __a : Union[str, Any] = del_node(self.root , snake_case_ ) def __str__(self : List[str] , ): # a level traversale, gives a more intuitive look on the tree __a : Union[str, Any] = '''''' __a : int = MyQueue() q.push(self.root ) __a : List[str] = self.get_height() if layer == 0: return output __a : List[Any] = 0 while not q.is_empty(): __a : List[str] = q.pop() __a : Optional[int] = ''' ''' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(snake_case_ ) q.push(snake_case_ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space __a : int = cnt + 1 for i in range(1_0_0 ): if cnt == math.pow(2 , snake_case_ ) - 1: __a : str = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __UpperCamelCase ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() lowercase__ =AVLtree() lowercase__ =list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
216
1
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : str = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase : int = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } _lowerCamelCase : List[Any] = { '''allenai/led-base-16384''': 1_63_84, } class lowercase ( a ): lowercase__ : Tuple = VOCAB_FILES_NAMES lowercase__ : Any = PRETRAINED_VOCAB_FILES_MAP lowercase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ : Optional[Any] = LEDTokenizer lowercase__ : str = ["""input_ids""", """attention_mask"""] def __init__( self : Union[str, Any] , _UpperCamelCase : Tuple=None , _UpperCamelCase : str=None , _UpperCamelCase : Tuple=None , _UpperCamelCase : List[str]="replace" , _UpperCamelCase : str="<s>" , _UpperCamelCase : List[Any]="</s>" , _UpperCamelCase : List[Any]="</s>" , _UpperCamelCase : List[str]="<s>" , _UpperCamelCase : Tuple="<unk>" , _UpperCamelCase : List[Any]="<pad>" , _UpperCamelCase : Tuple="<mask>" , _UpperCamelCase : List[str]=False , _UpperCamelCase : List[Any]=True , **_UpperCamelCase : Optional[Any] , ) -> Tuple: '''simple docstring''' super().__init__( _UpperCamelCase , _UpperCamelCase , tokenizer_file=_UpperCamelCase , errors=_UpperCamelCase , bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , sep_token=_UpperCamelCase , cls_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , add_prefix_space=_UpperCamelCase , trim_offsets=_UpperCamelCase , **_UpperCamelCase , ) SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , _UpperCamelCase ) != add_prefix_space: SCREAMING_SNAKE_CASE = getattr(_UpperCamelCase , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE = add_prefix_space SCREAMING_SNAKE_CASE = pre_tok_class(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE = "post_processor" SCREAMING_SNAKE_CASE = getattr(self.backend_tokenizer , _UpperCamelCase , _UpperCamelCase ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE = tuple(state["sep"] ) if "cls" in state: SCREAMING_SNAKE_CASE = tuple(state["cls"] ) SCREAMING_SNAKE_CASE = False if state.get("add_prefix_space" , _UpperCamelCase ) != add_prefix_space: SCREAMING_SNAKE_CASE = add_prefix_space SCREAMING_SNAKE_CASE = True if state.get("trim_offsets" , _UpperCamelCase ) != trim_offsets: SCREAMING_SNAKE_CASE = trim_offsets SCREAMING_SNAKE_CASE = True if changes_to_apply: SCREAMING_SNAKE_CASE = getattr(_UpperCamelCase , state.pop("type" ) ) SCREAMING_SNAKE_CASE = component_class(**_UpperCamelCase ) setattr(self.backend_tokenizer , _UpperCamelCase , _UpperCamelCase ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def __snake_case( self : int ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __snake_case( self : Optional[int] , _UpperCamelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else value SCREAMING_SNAKE_CASE = value def __snake_case( self : List[Any] , *_UpperCamelCase : Optional[int] , **_UpperCamelCase : Union[str, Any] ) -> BatchEncoding: '''simple docstring''' SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , _UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : int , *_UpperCamelCase : Dict , **_UpperCamelCase : Tuple ) -> BatchEncoding: '''simple docstring''' SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , _UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : List[Any] , _UpperCamelCase : str , _UpperCamelCase : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = self._tokenizer.model.save(_UpperCamelCase , name=_UpperCamelCase ) return tuple(_UpperCamelCase ) def __snake_case( self : List[Any] , _UpperCamelCase : List[Any] , _UpperCamelCase : int=None ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [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 __snake_case( self : Dict , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [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 __snake_case( self : Optional[Any] , _UpperCamelCase : Union[Dict[str, EncodedInput], BatchEncoding] , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : Optional[bool] = None , ) -> dict: '''simple docstring''' SCREAMING_SNAKE_CASE = super()._pad( encoded_inputs=_UpperCamelCase , max_length=_UpperCamelCase , padding_strategy=_UpperCamelCase , pad_to_multiple_of=_UpperCamelCase , return_attention_mask=_UpperCamelCase , ) # Load from model defaults if return_attention_mask is None: SCREAMING_SNAKE_CASE = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: SCREAMING_SNAKE_CASE = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. SCREAMING_SNAKE_CASE = len(encoded_inputs["global_attention_mask"] ) != len(_UpperCamelCase ) if needs_to_be_padded: SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` SCREAMING_SNAKE_CASE = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": SCREAMING_SNAKE_CASE = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
370
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowerCamelCase : str = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ): return [ int(1_0_0_0 * (box[0] / width) ), int(1_0_0_0 * (box[1] / height) ), int(1_0_0_0 * (box[2] / width) ), int(1_0_0_0 * (box[3] / height) ), ] def __lowerCamelCase (UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] ): SCREAMING_SNAKE_CASE = to_pil_image(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pil_image.size SCREAMING_SNAKE_CASE = pytesseract.image_to_data(UpperCAmelCase__ , lang=UpperCAmelCase__ , output_type="dict" , config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE = [idx for idx, word in enumerate(UpperCAmelCase__ ) if not word.strip()] SCREAMING_SNAKE_CASE = [word for idx, word in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE = [] for x, y, w, h in zip(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE = [x, y, x + w, y + h] actual_boxes.append(UpperCAmelCase__ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE = [] for box in actual_boxes: normalized_boxes.append(normalize_box(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) ) assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase ( a ): lowercase__ : Optional[int] = ["""pixel_values"""] def __init__( self : int , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : bool = True , _UpperCamelCase : float = 1 / 255 , _UpperCamelCase : bool = True , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : bool = True , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = "" , **_UpperCamelCase : Union[str, Any] , ) -> None: '''simple docstring''' super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_value SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD SCREAMING_SNAKE_CASE = apply_ocr SCREAMING_SNAKE_CASE = ocr_lang SCREAMING_SNAKE_CASE = tesseract_config def __snake_case( self : Dict , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : List[Any] , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) 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()}" ) SCREAMING_SNAKE_CASE = (size["height"], size["width"]) return resize(_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Union[str, Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[int, float] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Optional[int] , ) -> np.ndarray: '''simple docstring''' return rescale(_UpperCamelCase , scale=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : int , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[float, Iterable[float]] , _UpperCamelCase : Union[float, Iterable[float]] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Optional[Any] , ) -> np.ndarray: '''simple docstring''' return normalize(_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Tuple , _UpperCamelCase : ImageInput , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : bool = None , _UpperCamelCase : float = None , _UpperCamelCase : bool = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : bool = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[Union[str, TensorType]] = None , _UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCamelCase : List[Any] , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE = make_list_of_images(_UpperCamelCase ) if not valid_images(_UpperCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("If do_normalize is True, image_mean and image_std must be specified." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(_UpperCamelCase ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , "pytesseract" ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for image in images: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = apply_tesseract(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) words_batch.append(_UpperCamelCase ) boxes_batch.append(_UpperCamelCase ) if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=_UpperCamelCase , scale=_UpperCamelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE = [self.normalize(image=_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(_UpperCamelCase , _UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = BatchFeature(data={"pixel_values": images} , tensor_type=_UpperCamelCase ) if apply_ocr: SCREAMING_SNAKE_CASE = words_batch SCREAMING_SNAKE_CASE = boxes_batch return data
206
0
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> int: snake_case : List[str] = [1] snake_case , snake_case , snake_case : int = 0, 0, 0 snake_case : Tuple = ugly_nums[ia] * 2 snake_case : List[Any] = ugly_nums[ia] * 3 snake_case : Any = ugly_nums[ia] * 5 for _ in range(1 ,lowercase ): snake_case : List[str] = min(lowercase ,lowercase ,lowercase ) ugly_nums.append(lowercase ) if next_num == next_a: ia += 1 snake_case : Optional[int] = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 snake_case : Optional[Any] = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 snake_case : Tuple = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"""{ugly_numbers(2_0_0) = }""")
124
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> list: if len(lowercase ) != 2 or len(a[0] ) != 2 or len(lowercase ) != 2 or len(b[0] ) != 2: raise Exception("""Matrices are not 2x2""" ) snake_case : int = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowercase ) ) ] def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> str: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowercase ) ) ] def SCREAMING_SNAKE_CASE__ ( lowercase ) -> tuple[list, list, list, list]: if len(lowercase ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("""Odd matrices are not supported!""" ) snake_case : Optional[int] = len(lowercase ) snake_case : str = matrix_length // 2 snake_case : int = [[a[i][j] for j in range(lowercase ,lowercase )] for i in range(lowercase )] snake_case : str = [ [a[i][j] for j in range(lowercase ,lowercase )] for i in range(lowercase ,lowercase ) ] snake_case : Optional[Any] = [[a[i][j] for j in range(lowercase )] for i in range(lowercase )] snake_case : str = [[a[i][j] for j in range(lowercase )] for i in range(lowercase ,lowercase )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowercase ) -> tuple[int, int]: return len(lowercase ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowercase ) -> None: print("""\n""".join(str(lowercase ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> list: if matrix_dimensions(lowercase ) == (2, 2): return default_matrix_multiplication(lowercase ,lowercase ) snake_case , snake_case , snake_case , snake_case : Optional[Any] = split_matrix(lowercase ) snake_case , snake_case , snake_case , snake_case : Any = split_matrix(lowercase ) snake_case : List[Any] = actual_strassen(lowercase ,matrix_subtraction(lowercase ,lowercase ) ) snake_case : List[str] = actual_strassen(matrix_addition(lowercase ,lowercase ) ,lowercase ) snake_case : Tuple = actual_strassen(matrix_addition(lowercase ,lowercase ) ,lowercase ) snake_case : str = actual_strassen(lowercase ,matrix_subtraction(lowercase ,lowercase ) ) snake_case : Union[str, Any] = actual_strassen(matrix_addition(lowercase ,lowercase ) ,matrix_addition(lowercase ,lowercase ) ) snake_case : int = actual_strassen(matrix_subtraction(lowercase ,lowercase ) ,matrix_addition(lowercase ,lowercase ) ) snake_case : List[Any] = actual_strassen(matrix_subtraction(lowercase ,lowercase ) ,matrix_addition(lowercase ,lowercase ) ) snake_case : str = matrix_addition(matrix_subtraction(matrix_addition(lowercase ,lowercase ) ,lowercase ) ,lowercase ) snake_case : List[str] = matrix_addition(lowercase ,lowercase ) snake_case : Any = matrix_addition(lowercase ,lowercase ) snake_case : List[str] = matrix_subtraction(matrix_subtraction(matrix_addition(lowercase ,lowercase ) ,lowercase ) ,lowercase ) # construct the new matrix from our 4 quadrants snake_case : Optional[Any] = [] for i in range(len(lowercase ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowercase ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> list: if matrix_dimensions(lowercase )[1] != matrix_dimensions(lowercase )[0]: snake_case : Optional[Any] = ( """Unable to multiply these matrices, please check the dimensions.\n""" f"""Matrix A: {matrixa}\n""" f"""Matrix B: {matrixa}""" ) raise Exception(lowercase ) snake_case : str = matrix_dimensions(lowercase ) snake_case : Optional[Any] = matrix_dimensions(lowercase ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] snake_case : Dict = max(*lowercase ,*lowercase ) snake_case : Optional[Any] = int(math.pow(2 ,math.ceil(math.loga(lowercase ) ) ) ) snake_case : Any = matrixa snake_case : Optional[Any] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 ,lowercase ): if i < dimensiona[0]: for _ in range(dimensiona[1] ,lowercase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] ,lowercase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) snake_case : Optional[int] = actual_strassen(lowercase ,lowercase ) # Removing the additional zeros for i in range(0 ,lowercase ): if i < dimensiona[0]: for _ in range(dimensiona[1] ,lowercase ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": lowerCamelCase : Any = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] lowerCamelCase : int = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
124
1
"""simple docstring""" from math import factorial def lowercase (SCREAMING_SNAKE_CASE_ : int = 1_00 ) -> int: return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
38
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowercase (SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> Union[str, Any]: return params[F'{prefix}/{prefix}/relpos_bias/rel_embedding'][:, i, :] def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int]="attention" ) -> List[Any]: SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/key/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) SCREAMING_SNAKE_CASE = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/out/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) SCREAMING_SNAKE_CASE = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/query/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) SCREAMING_SNAKE_CASE = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/value/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def lowercase (SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any=False ) -> List[Any]: if split_mlp_wi: SCREAMING_SNAKE_CASE = params[F'{prefix}/{prefix}/mlp/wi_0/kernel'][:, i, :] SCREAMING_SNAKE_CASE = params[F'{prefix}/{prefix}/mlp/wi_1/kernel'][:, i, :] SCREAMING_SNAKE_CASE = (wi_a, wi_a) else: SCREAMING_SNAKE_CASE = params[F'{prefix}/{prefix}/mlp/wi/kernel'][:, i, :] SCREAMING_SNAKE_CASE = params[F'{prefix}/{prefix}/mlp/wo/kernel'][:, i, :] return wi, wo def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: return params[F'{prefix}/{prefix}/{layer_name}/scale'][:, i] def lowercase (SCREAMING_SNAKE_CASE_ : dict , *, SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : bool , SCREAMING_SNAKE_CASE_ : bool = False ) -> Tuple: SCREAMING_SNAKE_CASE = traverse_util.flatten_dict(variables['target'] ) SCREAMING_SNAKE_CASE = {'/'.join(SCREAMING_SNAKE_CASE_ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi SCREAMING_SNAKE_CASE = 'encoder/encoder/mlp/wi_0/kernel' in old print('Split MLP:' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = collections.OrderedDict() # Shared embeddings. SCREAMING_SNAKE_CASE = old['token_embedder/embedding'] # Encoder. for i in range(SCREAMING_SNAKE_CASE_ ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'encoder' , 'pre_attention_layer_norm' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'encoder' , 'attention' ) SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (MLP). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'encoder' , 'pre_mlp_layer_norm' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_mlp_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'encoder' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE = wi[0].T SCREAMING_SNAKE_CASE = wi[1].T else: SCREAMING_SNAKE_CASE = wi.T SCREAMING_SNAKE_CASE = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'encoder' ).T SCREAMING_SNAKE_CASE = old['encoder/encoder_norm/scale'] if not scalable_attention: SCREAMING_SNAKE_CASE = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE_ , 0 , 'encoder' ).T SCREAMING_SNAKE_CASE = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE_ , 0 , 'decoder' ).T if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE_ ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , 'pre_self_attention_layer_norm' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , 'self_attention' ) SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (Cross Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , 'pre_cross_attention_layer_norm' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , 'encoder_decoder_attention' ) SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 2 (MLP). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , 'pre_mlp_layer_norm' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_mlp_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE = wi[0].T SCREAMING_SNAKE_CASE = wi[1].T else: SCREAMING_SNAKE_CASE = wi.T SCREAMING_SNAKE_CASE = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE = tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'decoder' ).T SCREAMING_SNAKE_CASE = old['decoder/decoder_norm/scale'] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: SCREAMING_SNAKE_CASE = old['decoder/logits_dense/kernel'].T return new def lowercase (SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : bool ) -> int: SCREAMING_SNAKE_CASE = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) SCREAMING_SNAKE_CASE = state_dict['shared.weight'] return state_dict def lowercase (SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = convert_tax_to_pytorch( SCREAMING_SNAKE_CASE_ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE_ , scalable_attention=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = make_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ , strict=SCREAMING_SNAKE_CASE_ ) def lowercase (SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Any: SCREAMING_SNAKE_CASE = MTaConfig.from_json_file(SCREAMING_SNAKE_CASE_ ) print(F'Building PyTorch model from configuration: {config}' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: SCREAMING_SNAKE_CASE = UMTaEncoderModel(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE_ ) print('Done' ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) __UpperCamelCase = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
38
1
from __future__ import annotations class A__ : def __init__( self , __magic_name__ = 0 ): lowerCamelCase : List[str] = key def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) lowerCamelCase : int = key or self.__key or 1 # make sure key is an appropriate size key %= 2_5_5 return [chr(ord(__magic_name__ ) ^ key ) for ch in content] def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) lowerCamelCase : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 2_5_5 return [chr(ord(__magic_name__ ) ^ key ) for ch in content] def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ = 0 ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) lowerCamelCase : Any = key or self.__key or 1 # make sure key can be any size while key > 2_5_5: key -= 2_5_5 # This will be returned lowerCamelCase : int = """""" for ch in content: ans += chr(ord(__magic_name__ ) ^ key ) return ans def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ = 0 ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) lowerCamelCase : List[Any] = key or self.__key or 1 # make sure key can be any size while key > 2_5_5: key -= 2_5_5 # This will be returned lowerCamelCase : Union[str, Any] = """""" for ch in content: ans += chr(ord(__magic_name__ ) ^ key ) return ans def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ = 0 ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) try: with open(__magic_name__ ) as fin, open("""encrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(__magic_name__ , __magic_name__ ) ) except OSError: return False return True def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) try: with open(__magic_name__ ) as fin, open("""decrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(__magic_name__ , __magic_name__ ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
287
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration _lowerCamelCase =5_0_0_0_0_0 _lowerCamelCase , _lowerCamelCase =os.path.split(__file__) _lowerCamelCase =os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json""")) @get_duration def _a ( lowerCamelCase, **lowerCamelCase ): lowerCamelCase : Optional[Any] = dataset.map(**lowerCamelCase ) @get_duration def _a ( lowerCamelCase, **lowerCamelCase ): lowerCamelCase : Optional[Any] = dataset.filter(**lowerCamelCase ) def _a ( ): lowerCamelCase : Optional[Any] = {"""num examples""": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase : Any = datasets.Features({"""text""": datasets.Value("""string""" ), """numbers""": datasets.Value("""float32""" )} ) lowerCamelCase : Tuple = generate_example_dataset( os.path.join(lowerCamelCase, """dataset.arrow""" ), lowerCamelCase, num_examples=lowerCamelCase ) lowerCamelCase : Tuple = transformers.AutoTokenizer.from_pretrained("""bert-base-cased""", use_fast=lowerCamelCase ) def tokenize(lowerCamelCase ): return tokenizer(examples["""text"""] ) lowerCamelCase : List[str] = map(lowerCamelCase ) lowerCamelCase : int = map(lowerCamelCase, batched=lowerCamelCase ) lowerCamelCase : int = map(lowerCamelCase, function=lambda lowerCamelCase : None, batched=lowerCamelCase ) with dataset.formatted_as(type="""numpy""" ): lowerCamelCase : Optional[int] = map(lowerCamelCase, function=lambda lowerCamelCase : None, batched=lowerCamelCase ) with dataset.formatted_as(type="""pandas""" ): lowerCamelCase : List[str] = map(lowerCamelCase, function=lambda lowerCamelCase : None, batched=lowerCamelCase ) with dataset.formatted_as(type="""torch""", columns="""numbers""" ): lowerCamelCase : List[str] = map(lowerCamelCase, function=lambda lowerCamelCase : None, batched=lowerCamelCase ) with dataset.formatted_as(type="""tensorflow""", columns="""numbers""" ): lowerCamelCase : Optional[int] = map(lowerCamelCase, function=lambda lowerCamelCase : None, batched=lowerCamelCase ) lowerCamelCase : int = map(lowerCamelCase, function=lowerCamelCase, batched=lowerCamelCase ) lowerCamelCase : Union[str, Any] = filter(lowerCamelCase ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(lowerCamelCase, """wb""" ) as f: f.write(json.dumps(lowerCamelCase ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
287
1
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowerCAmelCase__ : def __init__( self : str , snake_case__ : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = data UpperCAmelCase__ : Tuple = [0x67_452_301, 0xef_cda_b89, 0x98_bad_cfe, 0x10_325_476, 0xc3_d2e_1f0] @staticmethod def __a ( snake_case__ : Any , snake_case__ : str ): '''simple docstring''' return ((n << b) | (n >> (3_2 - b))) & 0xff_fff_fff def __a ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : str = B'''\x80''' + B'''\x00''' * (6_3 - (len(self.data ) + 8) % 6_4) UpperCAmelCase__ : Any = self.data + padding + struct.pack(">Q" , 8 * len(self.data ) ) return padded_data def __a ( self : Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 6_4] for i in range(0 , len(self.padded_data ) , 6_4 ) ] def __a ( self : Any , snake_case__ : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Tuple = list(struct.unpack(">16L" , _SCREAMING_SNAKE_CASE ) ) + [0] * 6_4 for i in range(1_6 , 8_0 ): UpperCAmelCase__ : str = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 1_4] ^ w[i - 1_6]) , 1 ) return w def __a ( self : int ): '''simple docstring''' UpperCAmelCase__ : str = self.padding() UpperCAmelCase__ : Optional[int] = self.split_blocks() for block in self.blocks: UpperCAmelCase__ : Optional[int] = self.expand_block(_SCREAMING_SNAKE_CASE ) UpperCAmelCase__ : List[str] = self.h for i in range(0 , 8_0 ): if 0 <= i < 2_0: UpperCAmelCase__ : List[Any] = (b & c) | ((~b) & d) UpperCAmelCase__ : Any = 0x5a_827_999 elif 2_0 <= i < 4_0: UpperCAmelCase__ : Union[str, Any] = b ^ c ^ d UpperCAmelCase__ : int = 0x6e_d9e_ba1 elif 4_0 <= i < 6_0: UpperCAmelCase__ : int = (b & c) | (b & d) | (c & d) UpperCAmelCase__ : Tuple = 0x8f_1bb_cdc elif 6_0 <= i < 8_0: UpperCAmelCase__ : Any = b ^ c ^ d UpperCAmelCase__ : Dict = 0xca_62c_1d6 UpperCAmelCase__ : Tuple = ( self.rotate(_SCREAMING_SNAKE_CASE , 5 ) + f + e + k + expanded_block[i] & 0xff_fff_fff, a, self.rotate(_SCREAMING_SNAKE_CASE , 3_0 ), c, d, ) UpperCAmelCase__ : List[str] = ( self.h[0] + a & 0xff_fff_fff, self.h[1] + b & 0xff_fff_fff, self.h[2] + c & 0xff_fff_fff, self.h[3] + d & 0xff_fff_fff, self.h[4] + e & 0xff_fff_fff, ) return ("{:08x}" * 5).format(*self.h ) def SCREAMING_SNAKE_CASE__ ( )-> str: '''simple docstring''' UpperCAmelCase__ : Dict = B'''Test String''' assert SHAaHash(snake_case ).final_hash() == hashlib.shaa(snake_case ).hexdigest() # noqa: S324 def SCREAMING_SNAKE_CASE__ ( )-> List[Any]: '''simple docstring''' UpperCAmelCase__ : int = argparse.ArgumentParser(description="Process some strings or files" ) parser.add_argument( "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument("--file" , dest="input_file" , help="Hash contents of a file" ) UpperCAmelCase__ : Tuple = parser.parse_args() UpperCAmelCase__ : int = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: UpperCAmelCase__ : List[Any] = f.read() else: UpperCAmelCase__ : str = bytes(snake_case , "utf-8" ) print(SHAaHash(snake_case ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
371
"""simple docstring""" from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Dict = logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCAmelCase__ ( __magic_name__ ): SCREAMING_SNAKE_CASE_ ='''efficientformer''' def __init__( self : List[Any] , snake_case__ : List[int] = [3, 2, 6, 4] , snake_case__ : List[int] = [4_8, 9_6, 2_2_4, 4_4_8] , snake_case__ : List[bool] = [True, True, True, True] , snake_case__ : int = 4_4_8 , snake_case__ : int = 3_2 , snake_case__ : int = 4 , snake_case__ : int = 7 , snake_case__ : int = 5 , snake_case__ : int = 8 , snake_case__ : int = 4 , snake_case__ : float = 0.0 , snake_case__ : int = 1_6 , snake_case__ : int = 3 , snake_case__ : int = 3 , snake_case__ : int = 3 , snake_case__ : int = 2 , snake_case__ : int = 1 , snake_case__ : float = 0.0 , snake_case__ : int = 1 , snake_case__ : bool = True , snake_case__ : bool = True , snake_case__ : float = 1e-5 , snake_case__ : str = "gelu" , snake_case__ : float = 0.02 , snake_case__ : float = 1e-12 , snake_case__ : int = 2_2_4 , snake_case__ : float = 1e-05 , **snake_case__ : str , ): '''simple docstring''' super().__init__(**snake_case__ ) UpperCAmelCase__ : int = hidden_act UpperCAmelCase__ : Optional[int] = hidden_dropout_prob UpperCAmelCase__ : List[str] = hidden_sizes UpperCAmelCase__ : Union[str, Any] = num_hidden_layers UpperCAmelCase__ : int = num_attention_heads UpperCAmelCase__ : List[Any] = initializer_range UpperCAmelCase__ : List[Any] = layer_norm_eps UpperCAmelCase__ : Optional[int] = patch_size UpperCAmelCase__ : Tuple = num_channels UpperCAmelCase__ : Optional[int] = depths UpperCAmelCase__ : Union[str, Any] = mlp_expansion_ratio UpperCAmelCase__ : Dict = downsamples UpperCAmelCase__ : Any = dim UpperCAmelCase__ : str = key_dim UpperCAmelCase__ : List[Any] = attention_ratio UpperCAmelCase__ : Optional[Any] = resolution UpperCAmelCase__ : Optional[Any] = pool_size UpperCAmelCase__ : Any = downsample_patch_size UpperCAmelCase__ : int = downsample_stride UpperCAmelCase__ : Dict = downsample_pad UpperCAmelCase__ : List[Any] = drop_path_rate UpperCAmelCase__ : Optional[Any] = num_metaad_blocks UpperCAmelCase__ : List[str] = distillation UpperCAmelCase__ : Dict = use_layer_scale UpperCAmelCase__ : List[Any] = layer_scale_init_value UpperCAmelCase__ : Optional[Any] = image_size UpperCAmelCase__ : Optional[int] = batch_norm_eps
298
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class snake_case_ ( __A ,unittest.TestCase ): __A : int = RoCBertTokenizer __A : List[str] = None __A : Dict = False __A : Optional[int] = True __A : List[Any] = filter_non_english def __UpperCamelCase ( self : Dict ) -> Any: super().setUp() lowercase__ : Dict = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] lowercase__ : List[str] = {} lowercase__ : List[str] = {} for i, value in enumerate(lowercase_ ): lowercase__ : Union[str, Any] = i lowercase__ : Tuple = i lowercase__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) lowercase__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(lowercase_ , lowercase_ , ensure_ascii=lowercase_ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(lowercase_ , lowercase_ , ensure_ascii=lowercase_ ) def __UpperCamelCase ( self : Dict ) -> List[str]: lowercase__ : str = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase__ : Any = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(lowercase_ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: lowercase__ : List[str] = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __UpperCamelCase ( self : List[str] ) -> Dict: lowercase__ : Optional[int] = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : List[str] ) -> Tuple: lowercase__ : int = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def __UpperCamelCase ( self : Dict ) -> List[str]: lowercase__ : Any = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: lowercase__ : Any = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: lowercase__ : str = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Optional[int] ) -> List[str]: lowercase__ : Optional[int] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: lowercase__ : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Tuple: lowercase__ : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Dict: lowercase__ : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowercase__ : Union[str, Any] = {} for i, token in enumerate(lowercase_ ): lowercase__ : Optional[Any] = i lowercase__ : Dict = RoCBertWordpieceTokenizer(vocab=lowercase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def __UpperCamelCase ( self : str ) -> Tuple: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def __UpperCamelCase ( self : Dict ) -> int: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def __UpperCamelCase ( self : Dict ) -> Any: lowercase__ : int = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowercase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: lowercase__ : Optional[Any] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(lowercase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __UpperCamelCase ( self : List[str] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase__ : Dict = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : List[Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' lowercase__ : str = tokenizer_r.encode_plus( lowercase_ , return_attention_mask=lowercase_ , return_token_type_ids=lowercase_ , return_offsets_mapping=lowercase_ , add_special_tokens=lowercase_ , ) lowercase__ : Any = tokenizer_r.do_lower_case if hasattr(lowercase_ , "do_lower_case" ) else False lowercase__ : Any = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: lowercase__ : Optional[Any] = ["的", "人", "有"] lowercase__ : Optional[Any] = "".join(lowercase_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase__ : Optional[Any] = True lowercase__ : str = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Any = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Optional[int] = tokenizer_p.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Optional[int] = tokenizer_r.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(lowercase_ ) lowercase__ : List[Any] = tokenizer_p.convert_ids_to_tokens(lowercase_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) lowercase__ : int = False lowercase__ : Any = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Union[str, Any] = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Dict = tokenizer_r.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : List[str] = tokenizer_p.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : List[Any] = tokenizer_r.convert_ids_to_tokens(lowercase_ ) lowercase__ : str = tokenizer_p.convert_ids_to_tokens(lowercase_ ) # it is expected that only the first Chinese character is not preceded by "##". lowercase__ : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowercase_ ) ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) @slow def __UpperCamelCase ( self : Tuple ) -> int: lowercase__ : Optional[int] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase__ : Any = tokenizer.encode("你好" , add_special_tokens=lowercase_ ) lowercase__ : Dict = tokenizer.encode("你是谁" , add_special_tokens=lowercase_ ) lowercase__ : str = tokenizer.build_inputs_with_special_tokens(lowercase_ ) lowercase__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowercase_ , lowercase_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: lowercase__ : List[str] = self.get_tokenizers(do_lower_case=lowercase_ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): lowercase__ : int = "你好,你是谁" lowercase__ : int = tokenizer.tokenize(lowercase_ ) lowercase__ : str = tokenizer.convert_tokens_to_ids(lowercase_ ) lowercase__ : Tuple = tokenizer.convert_tokens_to_shape_ids(lowercase_ ) lowercase__ : int = tokenizer.convert_tokens_to_pronunciation_ids(lowercase_ ) lowercase__ : int = tokenizer.prepare_for_model( lowercase_ , lowercase_ , lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Any = tokenizer.encode_plus(lowercase_ , add_special_tokens=lowercase_ ) self.assertEqual(lowercase_ , lowercase_ )
87
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
0
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: _enforce_args(_UpperCAmelCase , _UpperCAmelCase ) if n == 0: return 0 lowerCamelCase__ : Tuple = float('-inf' ) for i in range(1 , n + 1 ): lowerCamelCase__ : str = max( _UpperCAmelCase , prices[i - 1] + naive_cut_rod_recursive(n - i , _UpperCAmelCase ) ) return max_revue def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: _enforce_args(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Tuple: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: lowerCamelCase__ : Dict = float('-inf' ) for i in range(1 , n + 1 ): lowerCamelCase__ : Tuple = max( _UpperCAmelCase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , _UpperCAmelCase , _UpperCAmelCase ) , ) lowerCamelCase__ : Dict = max_revenue return max_rev[n] def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Optional[Any]: _enforce_args(_UpperCAmelCase , _UpperCAmelCase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. lowerCamelCase__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] lowerCamelCase__ : List[str] = 0 for i in range(1 , n + 1 ): lowerCamelCase__ : Dict = max_rev[i] for j in range(1 , i + 1 ): lowerCamelCase__ : Union[str, Any] = max(_UpperCAmelCase , prices[j - 1] + max_rev[i - j] ) lowerCamelCase__ : List[str] = max_revenue_i return max_rev[n] def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: if n < 0: lowerCamelCase__ : Union[str, Any] = F"""n must be greater than or equal to 0. Got n = {n}""" raise ValueError(_UpperCAmelCase ) if n > len(_UpperCAmelCase ): lowerCamelCase__ : str = ( 'Each integral piece of rod must have a corresponding price. ' F"""Got n = {n} but length of prices = {len(_UpperCAmelCase )}""" ) raise ValueError(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( ) -> str: lowerCamelCase__ : Tuple = [6, 10, 12, 15, 20, 23] lowerCamelCase__ : Optional[Any] = len(_UpperCAmelCase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. lowerCamelCase__ : str = 36 lowerCamelCase__ : List[str] = top_down_cut_rod(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : str = bottom_up_cut_rod(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : str = naive_cut_rod_recursive(_UpperCAmelCase , _UpperCAmelCase ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
367
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder _UpperCAmelCase : Any = datasets.utils.logging.get_logger(__name__) class lowerCAmelCase ( folder_based_builder.FolderBasedBuilderConfig ): UpperCAmelCase__ = None UpperCAmelCase__ = None class lowerCAmelCase ( folder_based_builder.FolderBasedBuilder ): UpperCAmelCase__ = datasets.Audio() UpperCAmelCase__ = """audio""" UpperCAmelCase__ = AudioFolderConfig UpperCAmelCase__ = 42 # definition at the bottom of the script UpperCAmelCase__ = AudioClassification(audio_column="""audio""", label_column="""label""" ) _UpperCAmelCase : Union[str, Any] = [ """.aiff""", """.au""", """.avr""", """.caf""", """.flac""", """.htk""", """.svx""", """.mat4""", """.mat5""", """.mpc2k""", """.ogg""", """.paf""", """.pvf""", """.raw""", """.rf64""", """.sd2""", """.sds""", """.ircam""", """.voc""", """.w64""", """.wav""", """.nist""", """.wavex""", """.wve""", """.xi""", """.mp3""", """.opus""", ] _UpperCAmelCase : Union[str, Any] = AUDIO_EXTENSIONS
45
0
import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig _lowercase : Tuple ={ "facebook/maskformer-swin-base-ade": ( "https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json" ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } _lowercase : Optional[int] =logging.get_logger(__name__) class snake_case__ (A__ ): """simple docstring""" __lowerCAmelCase :Dict = "maskformer" __lowerCAmelCase :Any = {"hidden_size": "mask_feature_size"} __lowerCAmelCase :Tuple = ["resnet", "swin"] __lowerCAmelCase :Any = ["detr"] def __init__( self , __lowercase = 2_5_6 , __lowercase = 2_5_6 , __lowercase = 0.1 , __lowercase = False , __lowercase = None , __lowercase = None , __lowercase = 0.0_2 , __lowercase = 1.0 , __lowercase = 1.0 , __lowercase = 1.0 , __lowercase = 2_0.0 , __lowercase = None , **__lowercase , ) -> Optional[Any]: """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k a__ : str = SwinConfig( image_size=3_8_4 , in_channels=3 , patch_size=4 , embed_dim=1_2_8 , depths=[2, 2, 1_8, 2] , num_heads=[4, 8, 1_6, 3_2] , window_size=1_2 , drop_path_rate=0.3 , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] , ) if isinstance(__lowercase , __lowercase ): a__ : int = backbone_config.pop("""model_type""" ) a__ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a__ : Union[str, Any] = config_class.from_dict(__lowercase ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ''' F'''Supported model types: {','.join(self.backbones_supported )}''' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 a__ : Union[str, Any] = DetrConfig() else: # verify that the decoder is supported a__ : Optional[int] = ( decoder_config.pop("""model_type""" ) if isinstance(__lowercase , __lowercase ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( F'''Transformer Decoder {decoder_type} not supported, please use one of''' F''' {','.join(self.decoders_supported )}''' ) if isinstance(__lowercase , __lowercase ): a__ : str = CONFIG_MAPPING[decoder_type] a__ : List[Any] = config_class.from_dict(__lowercase ) a__ : Optional[int] = backbone_config a__ : List[str] = decoder_config # main feature dimension for the model a__ : Optional[int] = fpn_feature_size a__ : str = mask_feature_size # initializer a__ : Optional[Any] = init_std a__ : int = init_xavier_std # Hungarian matcher && loss a__ : Optional[Any] = cross_entropy_weight a__ : Dict = dice_weight a__ : Optional[int] = mask_weight a__ : Any = use_auxiliary_loss a__ : int = no_object_weight a__ : Tuple = output_auxiliary_logits a__ : List[Any] = self.decoder_config.encoder_attention_heads a__ : Optional[int] = self.decoder_config.num_hidden_layers super().__init__(**__lowercase ) @classmethod def SCREAMING_SNAKE_CASE__( cls , __lowercase , __lowercase , **__lowercase ) -> int: """simple docstring""" return cls( backbone_config=__lowercase , decoder_config=__lowercase , **__lowercase , ) def SCREAMING_SNAKE_CASE__( self ) -> Dict[str, any]: """simple docstring""" a__ : Optional[Any] = copy.deepcopy(self.__dict__ ) a__ : Optional[Any] = self.backbone_config.to_dict() a__ : Any = self.decoder_config.to_dict() a__ : Optional[Any] = self.__class__.model_type return output
170
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers _lowercase : Dict ="3" print("Python version:", sys.version) print("transformers version:", transformers.__version__) try: import torch print("Torch version:", torch.__version__) print("Cuda available:", torch.cuda.is_available()) print("Cuda version:", torch.version.cuda) print("CuDNN version:", torch.backends.cudnn.version()) print("Number of GPUs available:", torch.cuda.device_count()) print("NCCL version:", torch.cuda.nccl.version()) except ImportError: print("Torch version:", None) try: import deepspeed print("DeepSpeed version:", deepspeed.__version__) except ImportError: print("DeepSpeed version:", None) try: import tensorflow as tf print("TensorFlow version:", tf.__version__) print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) except ImportError: print("TensorFlow version:", None)
170
1
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _A ( _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =tmp_path / 'cache' __lowercase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __lowercase =SqlDatasetReader( 'dataset' , 'sqlite:///' + sqlite_path , cache_dir=_lowerCAmelCase , keep_in_memory=_lowerCAmelCase ).read() _check_sql_dataset(_lowerCAmelCase , _lowerCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =tmp_path / 'cache' __lowercase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowercase =features.copy() if features else default_expected_features __lowercase =( Features({feature: Value(_lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) __lowercase =SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , features=_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() _check_sql_dataset(_lowerCAmelCase , _lowerCAmelCase ) def _A ( _lowerCAmelCase ): """simple docstring""" with contextlib.closing(sqlitea.connect(_lowerCAmelCase ) ) as con: __lowercase =con.cursor() cur.execute('SELECT * FROM dataset' ) for row in cur: yield row @require_sqlalchemy def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =tmp_path / 'cache' __lowercase =os.path.join(_lowerCAmelCase , 'tmp.sql' ) __lowercase =SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=_lowerCAmelCase ).read() SqlDatasetWriter(_lowerCAmelCase , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=1 ).write() __lowercase =iter_sql_file(_lowerCAmelCase ) __lowercase =iter_sql_file(_lowerCAmelCase ) for rowa, rowa in zip(_lowerCAmelCase , _lowerCAmelCase ): assert rowa == rowa @require_sqlalchemy def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =tmp_path / 'cache' __lowercase =os.path.join(_lowerCAmelCase , 'tmp.sql' ) __lowercase =SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=_lowerCAmelCase ).read() SqlDatasetWriter(_lowerCAmelCase , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=2 ).write() __lowercase =iter_sql_file(_lowerCAmelCase ) __lowercase =iter_sql_file(_lowerCAmelCase ) for rowa, rowa in zip(_lowerCAmelCase , _lowerCAmelCase ): assert rowa == rowa @require_sqlalchemy def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =tmp_path / 'cache' __lowercase =os.path.join(_lowerCAmelCase , 'tmp.sql' ) __lowercase =SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=_lowerCAmelCase ).read() with pytest.raises(_lowerCAmelCase ): SqlDatasetWriter(_lowerCAmelCase , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=0 ).write()
48
'''simple docstring''' import functools def _A ( _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" __lowercase =len(_lowerCAmelCase ) __lowercase =len(_lowerCAmelCase ) @functools.cache def min_distance(_lowerCAmelCase , _lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa __lowercase =int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _lowerCAmelCase ) , 1 + min_distance(_lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
48
1
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowercase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def lowercase__ ( snake_case_ :int ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , _A , ) if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): __UpperCAmelCase = [image] if isinstance(image[0] , PIL.Image.Image ): __UpperCAmelCase , __UpperCAmelCase = image[0].size __UpperCAmelCase , __UpperCAmelCase = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 __UpperCAmelCase = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __UpperCAmelCase = np.concatenate(_A , axis=0 ) __UpperCAmelCase = np.array(_A ).astype(np.floataa ) / 255.0 __UpperCAmelCase = image.transpose(0 , 3 , 1 , 2 ) __UpperCAmelCase = 2.0 * image - 1.0 __UpperCAmelCase = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): __UpperCAmelCase = torch.cat(_A , dim=0 ) return image def lowercase__ ( snake_case_ :Dict ): if isinstance(_A , torch.Tensor ): return mask elif isinstance(_A , PIL.Image.Image ): __UpperCAmelCase = [mask] if isinstance(mask[0] , PIL.Image.Image ): __UpperCAmelCase , __UpperCAmelCase = mask[0].size __UpperCAmelCase , __UpperCAmelCase = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __UpperCAmelCase = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] __UpperCAmelCase = np.concatenate(_A , axis=0 ) __UpperCAmelCase = mask.astype(np.floataa ) / 255.0 __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = torch.from_numpy(_A ) elif isinstance(mask[0] , torch.Tensor ): __UpperCAmelCase = torch.cat(_A , dim=0 ) return mask class _UpperCAmelCase ( A__ ): a__ : Optional[int] = 42 a__ : List[str] = 42 def __init__( self : List[Any] , _lowercase : List[Any] , _lowercase : Union[str, Any] ): super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) @torch.no_grad() def __call__( self : Dict , _lowercase : Union[torch.Tensor, PIL.Image.Image] , _lowercase : Union[torch.Tensor, PIL.Image.Image] , _lowercase : int = 2_50 , _lowercase : float = 0.0 , _lowercase : int = 10 , _lowercase : int = 10 , _lowercase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowercase : Optional[str] = "pil" , _lowercase : bool = True , ): __UpperCAmelCase = image __UpperCAmelCase = _preprocess_image(__lowerCamelCase ) __UpperCAmelCase = original_image.to(device=self.device , dtype=self.unet.dtype ) __UpperCAmelCase = _preprocess_mask(__lowerCamelCase ) __UpperCAmelCase = mask_image.to(device=self.device , dtype=self.unet.dtype ) __UpperCAmelCase = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__lowerCamelCase , __lowerCamelCase ) and len(__lowerCamelCase ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(__lowerCamelCase )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) __UpperCAmelCase = original_image.shape __UpperCAmelCase = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , self.device ) __UpperCAmelCase = eta __UpperCAmelCase = self.scheduler.timesteps[0] + 1 __UpperCAmelCase = generator[0] if isinstance(__lowerCamelCase , __lowerCamelCase ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual __UpperCAmelCase = self.unet(__lowerCamelCase , __lowerCamelCase ).sample # compute previous image: x_t -> x_t-1 __UpperCAmelCase = self.scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ).prev_sample else: # compute the reverse: x_t-1 -> x_t __UpperCAmelCase = self.scheduler.undo_step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) __UpperCAmelCase = t __UpperCAmelCase = (image / 2 + 0.5).clamp(0 , 1 ) __UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCAmelCase = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCamelCase )
332
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self : List[str] ) -> Tuple: SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , __lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__lowerCamelCase , __lowerCamelCase ) def lowercase_ ( self : List[str] , **__lowerCamelCase : Dict ) -> List[str]: return BertTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def lowercase_ ( self : Any , **__lowerCamelCase : List[str] ) -> Any: return BertTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def lowercase_ ( self : Optional[int] , **__lowerCamelCase : int ) -> Dict: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def lowercase_ ( self : Dict ) -> Dict: shutil.rmtree(self.tmpdirname ) def lowercase_ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowercase_ ( self : int ) -> str: SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __lowerCamelCase ) self.assertIsInstance(processor_fast.tokenizer , __lowerCamelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __lowerCamelCase ) self.assertIsInstance(processor_fast.image_processor , __lowerCamelCase ) def lowercase_ ( self : Optional[int] ) -> List[str]: SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) SCREAMING_SNAKE_CASE__ = self.get_image_processor(do_normalize=__lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def lowercase_ ( self : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = image_processor(__lowerCamelCase , return_tensors='''np''' ) SCREAMING_SNAKE_CASE__ = processor(images=__lowerCamelCase , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowercase_ ( self : Tuple ) -> List[Any]: SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = '''lower newer''' SCREAMING_SNAKE_CASE__ = processor(text=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = tokenizer(__lowerCamelCase , padding='''max_length''' , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowercase_ ( self : Optional[int] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = '''lower newer''' SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def lowercase_ ( self : Union[str, Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ = processor.batch_decode(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def lowercase_ ( self : int ) -> str: SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = AlignProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = '''lower newer''' SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
314
0
def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' if p < 2: raise ValueError('p should not be less than 2!' ) elif p == 2: return True snake_case_ = 4 snake_case_ = (1 << p) - 1 for _ in range(p - 2 ): snake_case_ = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
200
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : int = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class lowercase ( lowercase_ ): __SCREAMING_SNAKE_CASE : int = '''canine''' def __init__( self , snake_case=768 , snake_case=12 , snake_case=12 , snake_case=3072 , snake_case="gelu" , snake_case=0.1 , snake_case=0.1 , snake_case=1_6384 , snake_case=16 , snake_case=0.02 , snake_case=1e-1_2 , snake_case=0 , snake_case=0xE000 , snake_case=0xE001 , snake_case=4 , snake_case=4 , snake_case=8 , snake_case=1_6384 , snake_case=128 , **snake_case , ): super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps # Character config: snake_case_ = downsampling_rate snake_case_ = upsampling_kernel_size snake_case_ = num_hash_functions snake_case_ = num_hash_buckets snake_case_ = local_transformer_stride
200
1
import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class _lowercase : """simple docstring""" def __init__( self : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : Any = True , __lowerCamelCase : Any = False ): '''simple docstring''' lowerCamelCase__ : Tuple = scheduler lowerCamelCase__ : str = optimizers if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) else [optimizers] lowerCamelCase__ : int = split_batches lowerCamelCase__ : Union[str, Any] = step_with_optimizer lowerCamelCase__ : List[str] = GradientState() def lowerCAmelCase ( self : Optional[int] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : str ): '''simple docstring''' if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) 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(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step lowerCamelCase__ : Any = AcceleratorState().num_processes for _ in range(SCREAMING_SNAKE_CASE_ ): # 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(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.scheduler.get_last_lr() def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' return self.scheduler.state_dict() def lowerCAmelCase ( self : Dict , __lowerCamelCase : Union[str, Any] ): '''simple docstring''' self.scheduler.load_state_dict(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase ( self : Dict ): '''simple docstring''' return self.scheduler.get_lr() def lowerCAmelCase ( self : int , *__lowerCamelCase : Any , **__lowerCamelCase : Any ): '''simple docstring''' return self.scheduler.print_lr(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
184
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = StableDiffusionInstructPixaPixPipeline lowerCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowerCamelCase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCamelCase : Optional[int] = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase_ ( self ) -> int: torch.manual_seed(0 ) __lowerCamelCase : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) __lowerCamelCase : Union[str, Any] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) __lowerCamelCase : Optional[Any] = 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 ) __lowerCamelCase : Optional[int] = 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=10_00 , ) __lowerCamelCase : int = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Optional[int] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __lowerCamelCase : Optional[Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Dict: __lowerCamelCase : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCamelCase : int = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert('RGB' ) if str(SCREAMING_SNAKE_CASE_ ).startswith('mps' ): __lowerCamelCase : Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: __lowerCamelCase : Optional[int] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Tuple = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def lowercase_ ( self ) -> Union[str, Any]: __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Any = self.get_dummy_components() __lowerCamelCase : Tuple = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Optional[int] = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = sd_pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowercase_ ( self ) -> Union[str, Any]: __lowerCamelCase : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Union[str, Any] = self.get_dummy_components() __lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Tuple = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Union[str, Any] = 'french fries' __lowerCamelCase : List[Any] = sd_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Tuple = output.images __lowerCamelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[Any] = np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowercase_ ( self ) -> Tuple: __lowerCamelCase : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Union[str, Any] = self.get_dummy_components() __lowerCamelCase : Any = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : List[str] = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = [inputs['prompt']] * 2 __lowerCamelCase : Tuple = np.array(inputs['image'] ).astype(np.floataa ) / 2_5_5.0 __lowerCamelCase : List[str] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ).to(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Dict = image / 2 + 0.5 __lowerCamelCase : Optional[Any] = image.permute(0 , 3 , 1 , 2 ) __lowerCamelCase : Dict = image.repeat(2 , 1 , 1 , 1 ) __lowerCamelCase : int = sd_pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : Tuple = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) __lowerCamelCase : Union[str, Any] = np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowercase_ ( self ) -> Tuple: __lowerCamelCase : str = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : int = self.get_dummy_components() __lowerCamelCase : Union[str, Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' ) __lowerCamelCase : str = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Dict = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = sd_pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = [round(SCREAMING_SNAKE_CASE_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(SCREAMING_SNAKE_CASE_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) __lowerCamelCase : List[str] = np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowercase_ ( self ) -> List[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowercase_ ( self ) -> Optional[int]: __lowerCamelCase : Union[str, Any] = self.get_dummy_components() __lowerCamelCase : Tuple = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = VaeImageProcessor(do_resize=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = pipe(**self.get_dummy_inputs_by_type(SCREAMING_SNAKE_CASE_ , input_image_type='pt' ) )[0] __lowerCamelCase : Optional[Any] = components['vae'] __lowerCamelCase : Dict = self.get_dummy_inputs_by_type(SCREAMING_SNAKE_CASE_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): __lowerCamelCase : str = vae.encode(inputs[image_param] ).latent_dist.mode() __lowerCamelCase : str = pipe(**SCREAMING_SNAKE_CASE_ )[0] __lowerCamelCase : Optional[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(SCREAMING_SNAKE_CASE_ , 1E-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class UpperCAmelCase_ (unittest.TestCase ): """simple docstring""" def lowercase_ ( self ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self , SCREAMING_SNAKE_CASE_=0 ) -> str: __lowerCamelCase : str = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Any = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) __lowerCamelCase : Any = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def lowercase_ ( self ) -> str: __lowerCamelCase : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() __lowerCamelCase : Optional[Any] = self.get_inputs() __lowerCamelCase : List[str] = pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase : Any = np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowercase_ ( self ) -> Any: __lowerCamelCase : Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Any = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() __lowerCamelCase : Optional[Any] = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase : Optional[Any] = np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowercase_ ( self ) -> Optional[int]: __lowerCamelCase : Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() __lowerCamelCase : Union[str, Any] = self.get_inputs() __lowerCamelCase : str = pipe(**SCREAMING_SNAKE_CASE_ ).images __lowerCamelCase : Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase : Union[str, Any] = np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowercase_ ( self ) -> Optional[int]: __lowerCamelCase : Union[str, Any] = 0 def callback_fn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: __lowerCamelCase : List[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __lowerCamelCase : Any = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __lowerCamelCase : Union[str, Any] = latents[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: __lowerCamelCase : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __lowerCamelCase : List[Any] = latents[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 __lowerCamelCase : int = False __lowerCamelCase : Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) __lowerCamelCase : Optional[Any] = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() __lowerCamelCase : Optional[int] = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowercase_ ( self ) -> Union[str, Any]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCamelCase : Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) __lowerCamelCase : List[Any] = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Tuple = pipe(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Optional[Any] = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowercase_ ( self ) -> List[Any]: __lowerCamelCase : Optional[int] = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 __lowerCamelCase : Union[str, Any] = inputs['image'].resize((5_04, 5_04) ) __lowerCamelCase : int = 'timbrooks/instruct-pix2pix' __lowerCamelCase : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() __lowerCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Any = output.images[0] __lowerCamelCase : Optional[int] = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 5_04, 3) __lowerCamelCase : List[str] = np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3
185
0
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict UpperCAmelCase : Dict = namedtuple( '_TestCommandArgs', [ 'dataset', 'name', 'cache_dir', 'data_dir', 'all_configs', 'save_infos', 'ignore_verifications', 'force_redownload', 'clear_cache', ], defaults=[None, None, None, False, False, False, False, False], ) def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : int ) -> List[Any]: '''simple docstring''' return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def lowerCamelCase ( _UpperCamelCase : List[str] ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = _TestCommandArgs(dataset=a__ , all_configs=a__ , save_infos=a__ ) __UpperCAmelCase : Optional[int] = TestCommand(*a__ ) test_command.run() __UpperCAmelCase : Optional[int] = os.path.join(a__ , """README.md""" ) assert os.path.exists(a__ ) __UpperCAmelCase : str = DatasetInfosDict.from_directory(a__ ) __UpperCAmelCase : Union[str, Any] = DatasetInfosDict( { """default""": DatasetInfo( features=Features( { """tokens""": Sequence(Value("""string""" ) ), """ner_tags""": Sequence( ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ), """langs""": Sequence(Value("""string""" ) ), """spans""": Sequence(Value("""string""" ) ), } ) , splits=[ { """name""": """train""", """num_bytes""": 2_3_5_1_5_6_3, """num_examples""": 1_0_0_0_0, }, { """name""": """validation""", """num_bytes""": 2_3_8_4_1_8, """num_examples""": 1_0_0_0, }, ] , download_size=3_9_4_0_6_8_0 , dataset_size=2_5_8_9_9_8_1 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: __UpperCAmelCase ,__UpperCAmelCase : List[str] = getattr(dataset_infos["""default"""] , a__ ), getattr(expected_dataset_infos["""default"""] , a__ ) if key == "num_bytes": assert is_apercent_close(a__ , a__ ) elif key == "splits": assert list(a__ ) == list(a__ ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
371
"""simple docstring""" def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : Optional[int] ) -> Any: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : Optional[int] , _UpperCamelCase : List[Any] ) -> str: '''simple docstring''' __UpperCAmelCase : Dict = 0 while b > 0: if b & 1: __UpperCAmelCase : int = ((res % c) + (a % c)) % c a += a b >>= 1 return res
320
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class _A : def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str]=13 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Dict=24 , __SCREAMING_SNAKE_CASE : Optional[int]=16 , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=32 , __SCREAMING_SNAKE_CASE : Tuple=5 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[Any]=37 , __SCREAMING_SNAKE_CASE : List[str]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Optional[int]=0.1 , __SCREAMING_SNAKE_CASE : Optional[int]=10 , __SCREAMING_SNAKE_CASE : str=0.02 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=2 , __SCREAMING_SNAKE_CASE : List[Any]=2 , ): '''simple docstring''' __a = parent __a = batch_size __a = patch_size __a = max_length __a = num_mel_bins __a = is_training __a = use_labels __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 = type_sequence_label_size __a = initializer_range __a = scope __a = frequency_stride __a = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __a = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __a = (self.max_length - self.patch_size) // self.time_stride + 1 __a = frequency_out_dimension * time_out_dimension __a = num_patches + 2 def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' __a = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size) __a = self.get_config() return config, input_values, labels def _lowerCamelCase ( self : Any): '''simple docstring''' return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = ASTModel(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() __a = model(__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _lowerCamelCase ( self : str): '''simple docstring''' __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_values''': input_values} return config, inputs_dict @require_torch class _A ( __UpperCAmelCase ,__UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ : Dict = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) UpperCamelCase__ : int = ( {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel} if is_torch_available() else {} ) UpperCamelCase__ : str = False UpperCamelCase__ : Optional[int] = False UpperCamelCase__ : List[str] = False UpperCamelCase__ : Optional[int] = False def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = ASTModelTester(self) __a = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=37) def _lowerCamelCase ( self : Dict): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''') def _lowerCamelCase ( self : Dict): '''simple docstring''' pass def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__SCREAMING_SNAKE_CASE) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear)) def _lowerCamelCase ( self : List[str]): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__SCREAMING_SNAKE_CASE) __a = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''input_values'''] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : int): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE) @slow def _lowerCamelCase ( self : Dict): '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ASTModel.from_pretrained(__SCREAMING_SNAKE_CASE) self.assertIsNotNone(__SCREAMING_SNAKE_CASE) def __snake_case ( ): __a = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) __a , __a = torchaudio.load(_UpperCAmelCase ) return audio, sampling_rate @require_torch @require_torchaudio class _A ( unittest.TestCase ): @cached_property def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''') if is_torchaudio_available() else None ) @slow def _lowerCamelCase ( self : Dict): '''simple docstring''' __a = self.default_feature_extractor __a = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__SCREAMING_SNAKE_CASE) __a = self.default_feature_extractor __a , __a = prepare_audio() __a = audio.squeeze().numpy() __a = feature_extractor(__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , return_tensors='''pt''').to(__SCREAMING_SNAKE_CASE) # forward pass with torch.no_grad(): __a = model(**__SCREAMING_SNAKE_CASE) # verify the logits __a = torch.Size((1, 527)) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE) __a = torch.tensor([-0.87_60, -7.00_42, -8.66_02]).to(__SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4))
49
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin snake_case_ = get_tests_dir('fixtures/test_sentencepiece_bpe.model') class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase , unittest.TestCase ): A_ : List[Any] = BartphoTokenizer A_ : List[str] = False A_ : Optional[Any] = True def a (self : Tuple ): """simple docstring""" super().setUp() __snake_case = ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] __snake_case = dict(zip(a__ , range(len(a__ ) ) ) ) __snake_case = {'''unk_token''': '''<unk>'''} __snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''monolingual_vocab_file'''] ) with open(self.monolingual_vocab_file , '''w''' , encoding='''utf-8''' ) as fp: for token in vocab_tokens: fp.write(f"""{token} {vocab_tokens[token]}\n""" ) __snake_case = BartphoTokenizer(a__ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def a (self : str , **a__ : str ): """simple docstring""" kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **a__ ) def a (self : str , a__ : Any ): """simple docstring""" __snake_case = '''This is a là test''' __snake_case = '''This is a<unk><unk> test''' return input_text, output_text def a (self : Dict ): """simple docstring""" __snake_case = BartphoTokenizer(a__ , self.monolingual_vocab_file , **self.special_tokens_map ) __snake_case = '''This is a là test''' __snake_case = '''▁This ▁is ▁a ▁l à ▁t est'''.split() __snake_case = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) __snake_case = tokens + [tokenizer.unk_token] __snake_case = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ )
24
0
from math import asin, atan, cos, radians, sin, sqrt, tan lowercase_ = 637_8137.0 lowercase_ = 635_6752.31_4245 lowercase_ = 6_3_7_8_1_3_7 def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = (AXIS_A - AXIS_B) / AXIS_A __lowerCamelCase : List[str] = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE__ ) ) ) __lowerCamelCase : str = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE__ ) ) ) __lowerCamelCase : List[Any] = radians(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = radians(SCREAMING_SNAKE_CASE__ ) # Equation __lowerCamelCase : List[Any] = sin((phi_a - phi_a) / 2 ) __lowerCamelCase : int = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda __lowerCamelCase : List[str] = sqrt(sin_sq_phi + (cos(SCREAMING_SNAKE_CASE__ ) * cos(SCREAMING_SNAKE_CASE__ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
194
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm lowercase_ = logging.get_logger(__name__) @dataclass class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self: Any , **a: Optional[Any] ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCamelCase : str = deprecated_arg[3:] setattr(self , a , not kwargs.pop(a ) ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) __lowerCamelCase : str = kwargs.pop('torchscript' , self.torchscript ) __lowerCamelCase : int = kwargs.pop('torch_xla_tpu_print_metrics' , self.torch_xla_tpu_print_metrics ) __lowerCamelCase : Dict = kwargs.pop('fp16_opt_level' , self.fpaa_opt_level ) super().__init__(**a ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Trace the models using torchscript"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Print Xla/PyTorch tpu metrics"""} ) __snake_case = field( default="""O1""" , metadata={ """help""": ( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. """ """See details at https://nvidia.github.io/apex/amp.html""" ) } , ) @cached_property def _snake_case ( self: Dict ): requires_backends(self , ['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: __lowerCamelCase : Dict = torch.device('cpu' ) __lowerCamelCase : str = 0 elif is_torch_tpu_available(): __lowerCamelCase : Optional[int] = xm.xla_device() __lowerCamelCase : Dict = 0 else: __lowerCamelCase : Any = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __lowerCamelCase : Union[str, Any] = torch.cuda.device_count() return device, n_gpu @property def _snake_case ( self: Optional[Any] ): return is_torch_tpu_available() and self.tpu @property def _snake_case ( self: Union[str, Any] ): requires_backends(self , ['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def _snake_case ( self: int ): requires_backends(self , ['torch'] ) return self._setup_devices[0] @property def _snake_case ( self: Union[str, Any] ): requires_backends(self , ['torch'] ) return self._setup_devices[1] @property def _snake_case ( self: List[Any] ): return self.n_gpu > 0
194
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = { '''configuration_bert''': ['''BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BertConfig''', '''BertOnnxConfig'''], '''tokenization_bert''': ['''BasicTokenizer''', '''BertTokenizer''', '''WordpieceTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''BertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ '''BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BertForMaskedLM''', '''BertForMultipleChoice''', '''BertForNextSentencePrediction''', '''BertForPreTraining''', '''BertForQuestionAnswering''', '''BertForSequenceClassification''', '''BertForTokenClassification''', '''BertLayer''', '''BertLMHeadModel''', '''BertModel''', '''BertPreTrainedModel''', '''load_tf_weights_in_bert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ '''TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBertEmbeddings''', '''TFBertForMaskedLM''', '''TFBertForMultipleChoice''', '''TFBertForNextSentencePrediction''', '''TFBertForPreTraining''', '''TFBertForQuestionAnswering''', '''TFBertForSequenceClassification''', '''TFBertForTokenClassification''', '''TFBertLMHeadModel''', '''TFBertMainLayer''', '''TFBertModel''', '''TFBertPreTrainedModel''', ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''TFBertTokenizer'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ '''FlaxBertForCausalLM''', '''FlaxBertForMaskedLM''', '''FlaxBertForMultipleChoice''', '''FlaxBertForNextSentencePrediction''', '''FlaxBertForPreTraining''', '''FlaxBertForQuestionAnswering''', '''FlaxBertForSequenceClassification''', '''FlaxBertForTokenClassification''', '''FlaxBertModel''', '''FlaxBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
141
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE :int = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class A_ ( lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : List[str] = PegasusTokenizer _lowerCamelCase : int = PegasusTokenizerFast _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : List[str] = True def lowercase ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing _UpperCAmelCase = PegasusTokenizer(snake_case_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase ( self : Tuple ): return PegasusTokenizer.from_pretrained("google/pegasus-large" ) def lowercase ( self : Union[str, Any] , **snake_case_ : Union[str, Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **snake_case_ ) def lowercase ( self : Tuple , snake_case_ : Any ): return ("This is a test", "This is a test") def lowercase ( self : Optional[int] ): _UpperCAmelCase = "</s>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case_ ) , snake_case_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case_ ) , snake_case_ ) def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "</s>" ) self.assertEqual(vocab_keys[-1] , "v" ) self.assertEqual(len(snake_case_ ) , 1_1_0_3 ) def lowercase ( self : Any ): self.assertEqual(self.get_tokenizer().vocab_size , 1_1_0_3 ) def lowercase ( self : List[Any] ): _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = ( "Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important" " </s> <pad> <pad> <pad>" ) _UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=snake_case_ , add_special_tokens=snake_case_ ).input_ids[0] _UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=snake_case_ , add_special_tokens=snake_case_ ).input_ids[0] self.assertListEqual(snake_case_ , snake_case_ ) def lowercase ( self : Tuple ): _UpperCAmelCase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word _UpperCAmelCase = "<mask_1> To ensure a <mask_2> flow of bank resolutions." _UpperCAmelCase = [2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] _UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=snake_case_ ).input_ids[0] self.assertListEqual(snake_case_ , snake_case_ ) def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6_1_0_3 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_0_3 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_0_2_4 _UpperCAmelCase = "To ensure a smooth flow of bank resolutions." _UpperCAmelCase = [4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] _UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=snake_case_ ).input_ids[0] self.assertListEqual(snake_case_ , snake_case_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def lowercase ( self : int ): _UpperCAmelCase = ["This is going to be way too long." * 1_5_0, "short example"] _UpperCAmelCase = ["not super long but more than 5 tokens", "tiny"] _UpperCAmelCase = self._large_tokenizer(snake_case_ , padding=snake_case_ , truncation=snake_case_ , return_tensors="pt" ) _UpperCAmelCase = self._large_tokenizer( text_target=snake_case_ , max_length=5 , padding=snake_case_ , truncation=snake_case_ , return_tensors="pt" ) assert batch.input_ids.shape == (2, 1_0_2_4) assert batch.attention_mask.shape == (2, 1_0_2_4) assert targets["input_ids"].shape == (2, 5) assert len(snake_case_ ) == 2 # input_ids, attention_mask. @slow def lowercase ( self : Dict ): # fmt: off _UpperCAmelCase = {"input_ids": [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0_6, 1_3_0, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 5_4_1_8_9, 1_1_2_9, 1_1_1, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 9_1_1_4, 1_4_7_8_7, 1_2_1, 1_3_2_4_9, 1_5_8, 5_9_2, 9_5_6, 1_2_1, 1_4_6_2_1, 3_1_5_7_6, 1_4_3, 6_2_6_1_3, 1_0_8, 9_6_8_8, 9_3_0, 4_3_4_3_0, 1_1_5_6_2, 6_2_6_1_3, 3_0_4, 1_0_8, 1_1_4_4_3, 8_9_7, 1_0_8, 9_3_1_4, 1_7_4_1_5, 6_3_3_9_9, 1_0_8, 1_1_4_4_3, 7_6_1_4, 1_8_3_1_6, 1_1_8, 4_2_8_4, 7_1_4_8, 1_2_4_3_0, 1_4_3, 1_4_0_0, 2_5_7_0_3, 1_5_8, 1_1_1, 4_2_8_4, 7_1_4_8, 1_1_7_7_2, 1_4_3, 2_1_2_9_7, 1_0_6_4, 1_5_8, 1_2_2, 2_0_4, 3_5_0_6, 1_7_5_4, 1_1_3_3, 1_4_7_8_7, 1_5_8_1, 1_1_5, 3_3_2_2_4, 4_4_8_2, 1_1_1, 1_3_5_5, 1_1_0, 2_9_1_7_3, 3_1_7, 5_0_8_3_3, 1_0_8, 2_0_1_4_7, 9_4_6_6_5, 1_1_1, 7_7_1_9_8, 1_0_7, 1], [1_1_0, 6_2_6_1_3, 1_1_7, 6_3_8, 1_1_2, 1_1_3_3, 1_2_1, 2_0_0_9_8, 1_3_5_5, 7_9_0_5_0, 1_3_8_7_2, 1_3_5, 1_5_9_6, 5_3_5_4_1, 1_3_5_2, 1_4_1, 1_3_0_3_9, 5_5_4_2, 1_2_4, 3_0_2, 5_1_8, 1_1_1, 2_6_8, 2_9_5_6, 1_1_5, 1_4_9, 4_4_2_7, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_3_9, 1_2_3_5, 2_7_9_9, 1_8_2_8_9, 1_7_7_8_0, 2_0_4, 1_0_9, 9_4_7_4, 1_2_9_6, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case_ , model_name="google/bigbird-pegasus-large-arxiv" , revision="ba85d0851d708441f91440d509690f1ab6353415" , ) @require_sentencepiece @require_tokenizers class A_ ( lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : List[str] = PegasusTokenizer _lowerCamelCase : List[Any] = PegasusTokenizerFast _lowerCamelCase : int = True _lowerCamelCase : Union[str, Any] = True def lowercase ( self : Any ): super().setUp() # We have a SentencePiece fixture for testing _UpperCAmelCase = PegasusTokenizer(snake_case_ , offset=0 , mask_token_sent=snake_case_ , mask_token="[MASK]" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase ( self : Tuple ): return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv" ) def lowercase ( self : Optional[Any] , **snake_case_ : Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **snake_case_ ) def lowercase ( self : Union[str, Any] , snake_case_ : str ): return ("This is a test", "This is a test") def lowercase ( self : List[str] ): _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = ( "Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>" " <pad> <pad> <pad>" ) _UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=snake_case_ , add_special_tokens=snake_case_ ).input_ids[0] _UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=snake_case_ , add_special_tokens=snake_case_ ).input_ids[0] self.assertListEqual(snake_case_ , snake_case_ ) @require_torch def lowercase ( self : Tuple ): _UpperCAmelCase = ["This is going to be way too long." * 1_0_0_0, "short example"] _UpperCAmelCase = ["not super long but more than 5 tokens", "tiny"] _UpperCAmelCase = self._large_tokenizer(snake_case_ , padding=snake_case_ , truncation=snake_case_ , return_tensors="pt" ) _UpperCAmelCase = self._large_tokenizer( text_target=snake_case_ , max_length=5 , padding=snake_case_ , truncation=snake_case_ , return_tensors="pt" ) assert batch.input_ids.shape == (2, 4_0_9_6) assert batch.attention_mask.shape == (2, 4_0_9_6) assert targets["input_ids"].shape == (2, 5) assert len(snake_case_ ) == 2 # input_ids, attention_mask. def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = ( "This is an example string that is used to test the original TF implementation against the HF" " implementation" ) _UpperCAmelCase = self._large_tokenizer(snake_case_ ).input_ids self.assertListEqual( snake_case_ , [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1] , )
22
0
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = ["pixel_values"] def __init__( self , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = PILImageResampling.BILINEAR , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = 1 / 255 , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = None , **UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**UpperCAmelCase ) lowercase_ = size if size is not None else {"shortest_edge": 256} lowercase_ = get_size_dict(UpperCAmelCase , default_to_square=UpperCAmelCase ) lowercase_ = crop_size if crop_size is not None else {"height": 224, "width": 224} lowercase_ = get_size_dict(UpperCAmelCase , param_name="crop_size" ) lowercase_ = do_resize lowercase_ = size lowercase_ = resample lowercase_ = do_center_crop lowercase_ = crop_size lowercase_ = do_rescale lowercase_ = rescale_factor lowercase_ = do_normalize lowercase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowercase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = PILImageResampling.BICUBIC , UpperCAmelCase = None , **UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' lowercase_ = get_size_dict(UpperCAmelCase , default_to_square=UpperCAmelCase ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowercase_ = get_resize_output_image_size(UpperCAmelCase , size=size["shortest_edge"] , default_to_square=UpperCAmelCase ) return resize(UpperCAmelCase , size=UpperCAmelCase , resample=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None , **UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' lowercase_ = get_size_dict(UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(UpperCAmelCase , size=(size["height"], size["width"]) , data_format=UpperCAmelCase , **UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None , **UpperCAmelCase ) -> np.ndarray: '''simple docstring''' return rescale(UpperCAmelCase , scale=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None , **UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(UpperCAmelCase , mean=UpperCAmelCase , std=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = ChannelDimension.FIRST , **UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' lowercase_ = do_resize if do_resize is not None else self.do_resize lowercase_ = size if size is not None else self.size lowercase_ = get_size_dict(UpperCAmelCase , default_to_square=UpperCAmelCase ) lowercase_ = resample if resample is not None else self.resample lowercase_ = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase_ = crop_size if crop_size is not None else self.crop_size lowercase_ = get_size_dict(UpperCAmelCase , param_name="crop_size" ) lowercase_ = do_rescale if do_rescale is not None else self.do_rescale lowercase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase_ = do_normalize if do_normalize is not None else self.do_normalize lowercase_ = image_mean if image_mean is not None else self.image_mean lowercase_ = image_std if image_std is not None else self.image_std lowercase_ = make_list_of_images(UpperCAmelCase ) if not valid_images(UpperCAmelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowercase_ = [to_numpy_array(UpperCAmelCase ) for image in images] if do_resize: lowercase_ = [self.resize(image=UpperCAmelCase , size=UpperCAmelCase , resample=UpperCAmelCase ) for image in images] if do_center_crop: lowercase_ = [self.center_crop(image=UpperCAmelCase , size=UpperCAmelCase ) for image in images] if do_rescale: lowercase_ = [self.rescale(image=UpperCAmelCase , scale=UpperCAmelCase ) for image in images] if do_normalize: lowercase_ = [self.normalize(image=UpperCAmelCase , mean=UpperCAmelCase , std=UpperCAmelCase ) for image in images] lowercase_ = [to_channel_dimension_format(UpperCAmelCase , UpperCAmelCase ) for image in images] lowercase_ = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase , tensor_type=UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase = None ) -> str: '''simple docstring''' lowercase_ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase ) != len(UpperCAmelCase ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase ): lowercase_ = target_sizes.numpy() lowercase_ = [] for idx in range(len(UpperCAmelCase ) ): lowercase_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase ) lowercase_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase ) else: lowercase_ = logits.argmax(dim=1 ) lowercase_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
358
import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=13 , UpperCAmelCase=7 , UpperCAmelCase=6 , UpperCAmelCase=17 , UpperCAmelCase=23 , UpperCAmelCase=11 , UpperCAmelCase=True , ) -> Tuple: '''simple docstring''' lowercase_ = parent lowercase_ = batch_size lowercase_ = seq_length lowercase_ = act_dim lowercase_ = state_dim lowercase_ = hidden_size lowercase_ = max_length lowercase_ = is_training def A__ ( self ) -> Dict: '''simple docstring''' lowercase_ = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) lowercase_ = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) lowercase_ = floats_tensor((self.batch_size, self.seq_length, 1) ) lowercase_ = floats_tensor((self.batch_size, self.seq_length, 1) ) lowercase_ = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) lowercase_ = random_attention_mask((self.batch_size, self.seq_length) ) lowercase_ = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def A__ ( self ) -> Optional[int]: '''simple docstring''' return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' lowercase_ = DecisionTransformerModel(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() lowercase_ = model(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def A__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) = config_and_inputs lowercase_ = { "states": states, "actions": actions, "rewards": rewards, "returns_to_go": returns_to_go, "timesteps": timesteps, "attention_mask": attention_mask, } return config, inputs_dict @require_torch class __lowerCamelCase ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = (DecisionTransformerModel,) if is_torch_available() else () lowerCAmelCase__ = () lowerCAmelCase__ = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids lowerCAmelCase__ = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def A__ ( self ) -> Dict: '''simple docstring''' lowercase_ = DecisionTransformerModelTester(self ) lowercase_ = ConfigTester(self , config_class=UpperCAmelCase , hidden_size=37 ) def A__ ( self ) -> str: '''simple docstring''' self.config_tester.run_common_tests() def A__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase ) @slow def A__ ( self ) -> Tuple: '''simple docstring''' for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ = DecisionTransformerModel.from_pretrained(UpperCAmelCase ) self.assertIsNotNone(UpperCAmelCase ) def A__ ( self ) -> Any: '''simple docstring''' lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ = model_class(UpperCAmelCase ) lowercase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ = [*signature.parameters.keys()] lowercase_ = [ "states", "actions", "rewards", "returns_to_go", "timesteps", "attention_mask", ] self.assertListEqual(arg_names[: len(UpperCAmelCase )] , UpperCAmelCase ) @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def A__ ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ = 2 # number of steps of autoregressive prediction we will perform lowercase_ = 10 # defined by the RL environment, may be normalized lowercase_ = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert" ) lowercase_ = model.to(UpperCAmelCase ) lowercase_ = model.config torch.manual_seed(0 ) lowercase_ = torch.randn(1 , 1 , config.state_dim ).to(device=UpperCAmelCase , dtype=torch.floataa ) # env.reset() lowercase_ = torch.tensor( [[0.242793, -0.28693074, 0.8742613], [0.67815274, -0.08101085, -0.12952147]] , device=UpperCAmelCase ) lowercase_ = torch.tensor(UpperCAmelCase , device=UpperCAmelCase , dtype=torch.floataa ).reshape(1 , 1 , 1 ) lowercase_ = state lowercase_ = torch.zeros(1 , 0 , config.act_dim , device=UpperCAmelCase , dtype=torch.floataa ) lowercase_ = torch.zeros(1 , 0 , device=UpperCAmelCase , dtype=torch.floataa ) lowercase_ = torch.tensor(0 , device=UpperCAmelCase , dtype=torch.long ).reshape(1 , 1 ) for step in range(UpperCAmelCase ): lowercase_ = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=UpperCAmelCase )] , dim=1 ) lowercase_ = torch.cat([rewards, torch.zeros(1 , 1 , device=UpperCAmelCase )] , dim=1 ) lowercase_ = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): lowercase_ , lowercase_ , lowercase_ = model( states=UpperCAmelCase , actions=UpperCAmelCase , rewards=UpperCAmelCase , returns_to_go=UpperCAmelCase , timesteps=UpperCAmelCase , attention_mask=UpperCAmelCase , return_dict=UpperCAmelCase , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4 ) ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=UpperCAmelCase , dtype=torch.floataa ), 1.0, False, {}, ) lowercase_ = action_pred[0, -1] lowercase_ = torch.cat([states, state] , dim=1 ) lowercase_ = returns_to_go[0, -1] - reward lowercase_ = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) lowercase_ = torch.cat( [timesteps, torch.ones((1, 1) , device=UpperCAmelCase , dtype=torch.long ) * (step + 1)] , dim=1 )
297
0
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller UpperCAmelCase : int = 3 def _SCREAMING_SNAKE_CASE ( a ) -> int: print('Generating primitive root of p' ) while True: __A : str = random.randrange(3 , a ) if pow(a , 2 , a ) == 1: continue if pow(a , a , a ) == 1: continue return g def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Tuple = rabin_miller.generate_large_prime(a ) # select large prime number. __A : Any = primitive_root(a ) # one primitive root on modulo p. __A : Any = random.randrange(3 , a ) # private_key -> have to be greater than 2 for safety. __A : str = cryptomath.find_mod_inverse(pow(a , a , a ) , a ) __A : Union[str, Any] = (key_size, e_a, e_a, p) __A : Dict = (key_size, d) return public_key, private_key def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Any = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as fo: fo.write(F"""{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as fo: fo.write(F"""{private_key[0]},{private_key[1]}""" ) def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('elgamal' , 20_48 ) print('Key files generation successful' ) if __name__ == "__main__": main()
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from __future__ import annotations import numpy as np def snake_case ( snake_case__ :np.ndarray) -> tuple[np.ndarray, np.ndarray]: _A , _A = np.shape(snake_case__) if rows != columns: _A = ( """'table' has to be of square shaped array but got a """ F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(snake_case__) _A = np.zeros((rows, columns)) _A = np.zeros((rows, columns)) for i in range(snake_case__): for j in range(snake_case__): _A = sum(lower[i][k] * upper[k][j] for k in range(snake_case__)) if upper[j][j] == 0: raise ArithmeticError("""No LU decomposition exists""") _A = (table[i][j] - total) / upper[j][j] _A = 1 for j in range(snake_case__ , snake_case__): _A = sum(lower[i][k] * upper[k][j] for k in range(snake_case__)) _A = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
81
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate _SCREAMING_SNAKE_CASE = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} _SCREAMING_SNAKE_CASE = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': F'''🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results''', 'emoji': True, }, } ] _SCREAMING_SNAKE_CASE = 0 for log in Path().glob('*.log'): _SCREAMING_SNAKE_CASE = 0 with open(log, 'r') as f: for line in f: _SCREAMING_SNAKE_CASE = json.loads(line) if line.get('nodeid', '') != "": _SCREAMING_SNAKE_CASE = line['nodeid'] if line.get('duration', None) is not None: _SCREAMING_SNAKE_CASE = F'''{line["duration"]:.4f}''' if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) _SCREAMING_SNAKE_CASE = [] log.unlink() _SCREAMING_SNAKE_CASE = '' _SCREAMING_SNAKE_CASE = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = {} for test in failed_tests: _SCREAMING_SNAKE_CASE = test[0].split('::') _SCREAMING_SNAKE_CASE = data[0].split('/')[-1] if data[0] not in filesafailed: _SCREAMING_SNAKE_CASE = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) _SCREAMING_SNAKE_CASE = [test[0] for test in failed_table] _SCREAMING_SNAKE_CASE = list(set(files)) # Count number of instances in failed_tests _SCREAMING_SNAKE_CASE = [] for file in individual_files: table.append([file, len(filesafailed[file])]) _SCREAMING_SNAKE_CASE = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3_000: _SCREAMING_SNAKE_CASE = 'Too many failed tests, please see the full report in the Action results.' _SCREAMING_SNAKE_CASE = len(err) + 10 _SCREAMING_SNAKE_CASE = message[: 3_000 - offset] + F'''\n...\n```\n{err}''' print(F'''### {message}''') else: _SCREAMING_SNAKE_CASE = 'No failed tests! 🤗' print(F'''## {message}''') payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient _SCREAMING_SNAKE_CASE = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": _SCREAMING_SNAKE_CASE = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) _SCREAMING_SNAKE_CASE = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': F'''https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}''', }, } payload.append(action_button) _SCREAMING_SNAKE_CASE = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': F'''Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}''', } ], } payload.append(date_report) _SCREAMING_SNAKE_CASE = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) _SCREAMING_SNAKE_CASE = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name _SCREAMING_SNAKE_CASE = '' for i, row in enumerate(test_failures): if row[0] != test_class: _SCREAMING_SNAKE_CASE = row[0] else: _SCREAMING_SNAKE_CASE = '' _SCREAMING_SNAKE_CASE = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': F'''Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```''', }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
266
'''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 : def __init__(self , lowercase , lowercase=13 , lowercase=3 , lowercase=True , lowercase=True , lowercase=0.1 , lowercase=0.1 , lowercase=224 , lowercase=1000 , lowercase=[3, 3, 6, 4] , lowercase=[48, 56, 112, 220] , ): A_ : Dict = parent A_ : List[Any] = batch_size A_ : Dict = num_channels A_ : Optional[Any] = is_training A_ : List[str] = use_labels A_ : List[Any] = hidden_dropout_prob A_ : Optional[int] = attention_probs_dropout_prob A_ : Tuple = num_labels A_ : List[str] = image_size A_ : str = layer_depths A_ : Optional[int] = embed_dims def _a (self ): A_ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ : int = None if self.use_labels: A_ : Tuple = ids_tensor([self.batch_size] , self.num_labels ) A_ : int = self.get_config() return config, pixel_values, labels def _a (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=lowercase , layer_scale_init_value=1E-5 , ) def _a (self , lowercase , lowercase , lowercase ): A_ : List[Any] = SwiftFormerModel(config=lowercase ) model.to(lowercase ) model.eval() A_ : Union[str, Any] = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def _a (self , lowercase , lowercase , lowercase ): A_ : Any = self.num_labels A_ : Any = SwiftFormerForImageClassification(lowercase ) model.to(lowercase ) model.eval() A_ : Optional[int] = model(lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) A_ : int = SwiftFormerForImageClassification(lowercase ) model.to(lowercase ) model.eval() A_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ : Dict = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a (self ): ((A_), (A_), (A_)) : int = self.prepare_config_and_inputs() A_ : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () __SCREAMING_SNAKE_CASE : Optional[Any] = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE : int = False __SCREAMING_SNAKE_CASE : List[Any] = False __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False def _a (self ): A_ : Optional[int] = SwiftFormerModelTester(self ) A_ : Any = ConfigTester( self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def _a (self ): self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def _a (self ): pass def _a (self ): A_, A_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : Optional[Any] = model_class(lowercase ) A_ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase , nn.Linear ) ) def _a (self ): A_, A_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : str = model_class(lowercase ) A_ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ : int = [*signature.parameters.keys()] A_ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowercase ) def _a (self ): A_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase ) def _a (self ): A_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase ) @slow def _a (self ): for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : Optional[Any] = SwiftFormerModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def _a (self ): pass def _a (self ): def check_hidden_states_output(lowercase , lowercase , lowercase ): A_ : str = model_class(lowercase ) model.to(lowercase ) model.eval() with torch.no_grad(): A_ : Optional[int] = model(**self._prepare_for_class(lowercase , lowercase ) ) A_ : Any = outputs.hidden_states A_ : Any = 8 self.assertEqual(len(lowercase ) , lowercase ) # 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(lowercase ) ): 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_ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : str = True check_hidden_states_output(lowercase , lowercase , lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A_ : str = True check_hidden_states_output(lowercase , lowercase , lowercase ) def _a (self ): def _config_zero_init(lowercase ): A_ : Optional[Any] = copy.deepcopy(lowercase ) 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(lowercase , lowercase , 1E-10 ) if isinstance(getattr(lowercase , lowercase , lowercase ) , lowercase ): A_ : Any = _config_zero_init(getattr(lowercase , lowercase ) ) setattr(lowercase , lowercase , lowercase ) return configs_no_init A_, A_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() A_ : Any = _config_zero_init(lowercase ) for model_class in self.all_model_classes: A_ : List[str] = model_class(config=lowercase ) 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 _a (self ): pass def a ( ): '''simple docstring''' A_ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a (self ): return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def _a (self ): A_ : Any = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowercase ) A_ : Dict = self.default_image_processor A_ : Dict = prepare_img() A_ : int = image_processor(images=lowercase , return_tensors="""pt""" ).to(lowercase ) # forward pass with torch.no_grad(): A_ : int = model(**lowercase ) # verify the logits A_ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase ) A_ : List[str] = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1E-4 ) )
206
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def UpperCAmelCase_ (_lowerCAmelCase : List[str] ): __UpperCamelCase : List[Any] = [] for line in lines: __UpperCamelCase : int = re.sub(R"#.*" , "" , _lowerCAmelCase ) # remove comments if line: filtered_lines.append(_lowerCAmelCase ) __UpperCamelCase : List[str] = "\n".join(_lowerCAmelCase ) # Make a hash from all this code __UpperCamelCase : Union[str, Any] = full_str.encode("utf-8" ) return shaaaa(_lowerCAmelCase ).hexdigest() # get importable module names and hash for caching lowercase : str = { "csv": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), "json": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), "pandas": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), "parquet": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), "arrow": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), "text": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), "imagefolder": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), "audiofolder": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions lowercase : Dict = { ".csv": ("csv", {}), ".tsv": ("csv", {"sep": "\t"}), ".json": ("json", {}), ".jsonl": ("json", {}), ".parquet": ("parquet", {}), ".arrow": ("arrow", {}), ".txt": ("text", {}), } _EXTENSION_TO_MODULE.update({ext: ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) lowercase : List[str] = {"imagefolder", "audiofolder"} # Used to filter data files based on extensions given a module name lowercase : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(".zip") _MODULE_TO_EXTENSIONS["audiofolder"].append(".zip")
171
from math import sqrt def UpperCAmelCase_ (_lowerCAmelCase : int = 1_00_00_00 ): __UpperCamelCase : int = 0 __UpperCamelCase : int = 0 __UpperCamelCase : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(_lowerCAmelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F"""{solution() = }""")
171
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _A ( self : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase , num_images_per_prompt=__lowerCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
"""simple docstring""" from collections import namedtuple __lowerCamelCase = namedtuple("from_to", "from_ to") __lowerCamelCase = { "cubicmeter": from_to(1, 1), "litre": from_to(0.0_0_1, 10_00), "kilolitre": from_to(1, 1), "gallon": from_to(0.0_0_4_5_4, 2_64.1_72), "cubicyard": from_to(0.7_6_4_5_5, 1.3_0_7_9_5), "cubicfoot": from_to(0.0_2_8, 35.31_47), "cup": from_to(0.0_0_0_2_3_6_5_8_8, 42_26.75), } def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCamelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCamelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
358
"""simple docstring""" from functools import lru_cache def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" A__ = 2 A__ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase__ ) if n > 1: factors.add(UpperCamelCase__ ) return factors @lru_cache def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" return len(unique_prime_factors(UpperCamelCase__ ) ) def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" return len(set(UpperCamelCase__ ) ) in (0, 1) def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" A__ = 2 while True: # Increment each value of a generated range A__ = [base + i for i in range(UpperCamelCase__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. A__ = [upf_len(UpperCamelCase__ ) for x in group] checker.append(UpperCamelCase__ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase__ ): return group # Increment our base variable by 1 base += 1 def UpperCAmelCase ( UpperCamelCase__ = 4 ): """simple docstring""" A__ = run(UpperCamelCase__ ) return results[0] if len(UpperCamelCase__ ) else None if __name__ == "__main__": print(solution())
154
0
"""simple docstring""" import argparse import os import re import packaging.version __a = "examples/" __a = { "examples": (re.compile(r"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(r"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(r"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), r"\1version=\"VERSION\","), "doc": (re.compile(r"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } __a = { "init": "src/transformers/__init__.py", "setup": "setup.py", } __a = "README.md" def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' with open(_lowercase, """r""", encoding="""utf-8""", newline="""\n""" ) as f: snake_case_ :Optional[Any] = f.read() snake_case_, snake_case_ :int = REPLACE_PATTERNS[pattern] snake_case_ :int = replace.replace("""VERSION""", _lowercase ) snake_case_ :List[Any] = re_pattern.sub(_lowercase, _lowercase ) with open(_lowercase, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.write(_lowercase ) def A_ ( _lowercase ): '''simple docstring''' for folder, directories, fnames in os.walk(_lowercase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(_lowercase, _lowercase ), _lowercase, pattern="""examples""" ) def A_ ( _lowercase, _lowercase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_lowercase, _lowercase, _lowercase ) if not patch: update_version_in_examples(_lowercase ) def A_ ( ): '''simple docstring''' snake_case_ :Any = """🤗 Transformers currently provides the following architectures""" snake_case_ :str = """1. Want to contribute a new model?""" with open(_lowercase, """r""", encoding="""utf-8""", newline="""\n""" ) as f: snake_case_ :Union[str, Any] = f.readlines() # Find the start of the list. snake_case_ :Union[str, Any] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 snake_case_ :Tuple = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): snake_case_ :List[str] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""", """https://huggingface.co/docs/transformers/model_doc""", ) index += 1 with open(_lowercase, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(_lowercase ) def A_ ( ): '''simple docstring''' with open(REPLACE_FILES["""init"""], """r""" ) as f: snake_case_ :str = f.read() snake_case_ :str = REPLACE_PATTERNS["""init"""][0].search(_lowercase ).groups()[0] return packaging.version.parse(_lowercase ) def A_ ( _lowercase=False ): '''simple docstring''' snake_case_ :List[Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: snake_case_ :Optional[int] = default_version.base_version elif patch: snake_case_ :List[str] = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: snake_case_ :Union[str, Any] = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. snake_case_ :Dict = input(f"""Which version are you releasing? [{default_version}]""" ) if len(_lowercase ) == 0: snake_case_ :str = default_version print(f"""Updating version to {version}.""" ) global_version_update(_lowercase, patch=_lowercase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def A_ ( ): '''simple docstring''' snake_case_ :Optional[Any] = get_version() snake_case_ :str = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" snake_case_ :List[str] = current_version.base_version # Check with the user we got that right. snake_case_ :Union[str, Any] = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(_lowercase ) == 0: snake_case_ :Union[str, Any] = dev_version print(f"""Updating version to {version}.""" ) global_version_update(_lowercase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") __a = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
66
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCAmelCase ( snake_case__=None ): if subparsers is not None: __UpperCamelCase : Any = subparsers.add_parser("test" ) else: __UpperCamelCase : Dict = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=snake_case__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def __lowerCAmelCase ( snake_case__ ): __UpperCamelCase : str = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: __UpperCamelCase : str = script_name else: __UpperCamelCase : Tuple = F"--config_file={args.config_file} {script_name}" __UpperCamelCase : Optional[Any] = ["accelerate-launch"] + test_args.split() __UpperCamelCase : Optional[Any] = execute_subprocess_async(snake_case__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __lowerCAmelCase ( ): __UpperCamelCase : int = test_command_parser() __UpperCamelCase : Union[str, Any] = parser.parse_args() test_command(snake_case__ ) if __name__ == "__main__": main()
298
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_rembert import RemBertTokenizer else: lowerCamelCase__ : Dict = None lowerCamelCase__ : Any = logging.get_logger(__name__) lowerCamelCase__ : List[str] = {'vocab_file': 'sentencepiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase__ : List[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, 'tokenizer_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/tokenizer.json', }, } lowerCamelCase__ : Optional[Any] = { 'google/rembert': 256, } lowerCamelCase__ : List[Any] = '▁' class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = RemBertTokenizer def __init__( self : Dict , _lowerCAmelCase : Any=None , _lowerCAmelCase : List[str]=None , _lowerCAmelCase : List[str]=True , _lowerCAmelCase : Optional[Any]=True , _lowerCAmelCase : Any=False , _lowerCAmelCase : Optional[Any]="[CLS]" , _lowerCAmelCase : Union[str, Any]="[SEP]" , _lowerCAmelCase : Tuple="<unk>" , _lowerCAmelCase : Optional[Any]="[SEP]" , _lowerCAmelCase : Optional[Any]="<pad>" , _lowerCAmelCase : List[str]="[CLS]" , _lowerCAmelCase : int="[MASK]" , **_lowerCAmelCase : List[str] , ): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_ = AddedToken(_lowerCAmelCase , lstrip=_lowerCAmelCase , rstrip=_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ) else mask_token super().__init__( _lowerCAmelCase , tokenizer_file=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , remove_space=_lowerCAmelCase , keep_accents=_lowerCAmelCase , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , **_lowerCAmelCase , ) SCREAMING_SNAKE_CASE_ = do_lower_case SCREAMING_SNAKE_CASE_ = remove_space SCREAMING_SNAKE_CASE_ = keep_accents SCREAMING_SNAKE_CASE_ = vocab_file SCREAMING_SNAKE_CASE_ = False if not self.vocab_file else True def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : List[int] , _lowerCAmelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE_ = [self.sep_token_id] SCREAMING_SNAKE_CASE_ = [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 lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : List[int] , _lowerCAmelCase : Optional[List[int]] = None , _lowerCAmelCase : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_lowerCAmelCase )) + [1] + ([0] * len(_lowerCAmelCase )) + [1] return [1] + ([0] * len(_lowerCAmelCase )) + [1] def lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : List[int] , _lowerCAmelCase : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE_ = [self.sep_token_id] SCREAMING_SNAKE_CASE_ = [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 lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : str , _lowerCAmelCase : Optional[str] = None ): if not os.path.isdir(_lowerCAmelCase ): logger.error('Vocabulary path ({}) should be a directory'.format(_lowerCAmelCase ) ) return SCREAMING_SNAKE_CASE_ = os.path.join( _lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCAmelCase ): copyfile(self.vocab_file , _lowerCAmelCase ) return (out_vocab_file,)
210
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> int: if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE_ = version.parse(accelerate.__version__ ).base_version if version.parse(__UpperCAmelCase ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *__UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Optional[Any] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *__UpperCAmelCase , **__UpperCAmelCase ) return wrapper
210
1
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A( unittest.TestCase ): '''simple docstring''' def a__ ( self : str ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) lowerCamelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def a__ ( self : List[Any] ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : Tuple ) -> List[Any]: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : List[str] ) -> List[Any]: """simple docstring""" lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : str ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowerCamelCase : List[Any] = Accelerator() lowerCamelCase : List[Any] = (accelerator.state.process_index + 2, 10) lowerCamelCase : Dict = torch.randint(0, 10, shape).to(accelerator.device) lowerCamelCase : Tuple = "" lowerCamelCase : Optional[Any] = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowerCamelCase : Union[str, Any] = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowerCamelCase : Union[str, Any] = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
204
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
"""simple docstring""" import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class lowercase__ ( unittest.TestCase): @slow def __A ( self : Optional[int] ): '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = FlaxAutoModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) @slow def __A ( self : str ): '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: with self.subTest(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Dict = AutoConfig.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxAutoModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) @slow def __A ( self : List[str] ): '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = tokenizer('''Do you support jax jitted function?''' , return_tensors=TensorType.JAX ) @jax.jit def eval(**UpperCamelCase__ : Any ): return model(**UpperCamelCase__ ) eval(**UpperCamelCase__ ).block_until_ready() @slow def __A ( self : List[str] ): '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = FlaxRobertaModel.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = tokenizer('''Do you support jax jitted function?''' , return_tensors=TensorType.JAX ) @jax.jit def eval(**UpperCamelCase__ : Dict ): return model(**UpperCamelCase__ ) eval(**UpperCamelCase__ ).block_until_ready() def __A ( self : str ): '''simple docstring''' with self.assertRaisesRegex( UpperCamelCase__ , '''bert-base is not a local folder and is not a valid model identifier''' ): SCREAMING_SNAKE_CASE : Tuple = FlaxAutoModel.from_pretrained('''bert-base''' ) def __A ( self : List[Any] ): '''simple docstring''' with self.assertRaisesRegex( UpperCamelCase__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): SCREAMING_SNAKE_CASE : Tuple = FlaxAutoModel.from_pretrained(UpperCamelCase__ , revision='''aaaaaa''' ) def __A ( self : Optional[Any] ): '''simple docstring''' with self.assertRaisesRegex( UpperCamelCase__ , '''hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack''' , ): SCREAMING_SNAKE_CASE : List[Any] = FlaxAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def __A ( self : Optional[int] ): '''simple docstring''' with self.assertRaisesRegex(UpperCamelCase__ , '''Use `from_pt=True` to load this model''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' )
352
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 if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __UpperCamelCase : List[Any] = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = {'tokenizer_file': 'tokenizer.json'} __UpperCamelCase : str = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = ["""input_ids""", """attention_mask"""] UpperCamelCase_ = None def __init__( self : int , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[int]="<unk>" , UpperCamelCase__ : str="<s>" , UpperCamelCase__ : Dict="</s>" , UpperCamelCase__ : Any="<pad>" , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=False , **UpperCamelCase__ : List[str] , ): '''simple docstring''' super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , UpperCamelCase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE : int = getattr(UpperCamelCase__ , pre_tok_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Dict = add_prefix_space SCREAMING_SNAKE_CASE : List[Any] = pre_tok_class(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = add_prefix_space def __A ( self : Tuple , *UpperCamelCase__ : Any , **UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''is_split_into_words''' , UpperCamelCase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" ''' pretokenized inputs.''' ) return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[int] , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = kwargs.get('''is_split_into_words''' , UpperCamelCase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" ''' pretokenized inputs.''' ) return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : "Conversation" ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: SCREAMING_SNAKE_CASE : Optional[Any] = input_ids[-self.model_max_length :] return input_ids
258
0
import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Optional[int]: lowerCamelCase : Optional[Any] = 1.5 lowerCamelCase : Optional[int] = int(factor * num_class_images ) lowerCamelCase : str = ClipClient( url="https://knn.laion.ai/knn-service" ,indice_name="laion_400m" ,num_images=_SCREAMING_SNAKE_CASE ,aesthetic_weight=0.1 ) os.makedirs(f'''{class_data_dir}/images''' ,exist_ok=_SCREAMING_SNAKE_CASE ) if len(list(Path(f'''{class_data_dir}/images''' ).iterdir() ) ) >= num_class_images: return while True: lowerCamelCase : List[Any] = client.query(text=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) >= factor * num_class_images or num_images > 1e4: break else: lowerCamelCase : Any = int(factor * num_images ) lowerCamelCase : int = ClipClient( url="https://knn.laion.ai/knn-service" ,indice_name="laion_400m" ,num_images=_SCREAMING_SNAKE_CASE ,aesthetic_weight=0.1 ,) lowerCamelCase : Any = 0 lowerCamelCase : str = 0 lowerCamelCase : Dict = tqdm(desc="downloading real regularization images" ,total=_SCREAMING_SNAKE_CASE ) with open(f'''{class_data_dir}/caption.txt''' ,"w" ) as fa, open(f'''{class_data_dir}/urls.txt''' ,"w" ) as fa, open( f'''{class_data_dir}/images.txt''' ,"w" ) as fa: while total < num_class_images: lowerCamelCase : str = class_images[count] count += 1 try: lowerCamelCase : Union[str, Any] = requests.get(images["url"] ) if img.status_code == 200: lowerCamelCase : Dict = Image.open(BytesIO(img.content ) ) with open(f'''{class_data_dir}/images/{total}.jpg''' ,"wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f'''{class_data_dir}/images/{total}.jpg''' + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def A ( ) -> List[Any]: lowerCamelCase : Dict = argparse.ArgumentParser("" ,add_help=_SCREAMING_SNAKE_CASE ) parser.add_argument("--class_prompt" ,help="text prompt to retrieve images" ,required=_SCREAMING_SNAKE_CASE ,type=_SCREAMING_SNAKE_CASE ) parser.add_argument("--class_data_dir" ,help="path to save images" ,required=_SCREAMING_SNAKE_CASE ,type=_SCREAMING_SNAKE_CASE ) parser.add_argument("--num_class_images" ,help="number of images to download" ,default=200 ,type=_SCREAMING_SNAKE_CASE ) return parser.parse_args() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
48
import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Dict: # Initialise PyTorch model lowerCamelCase : Any = TaConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(f'''Building PyTorch model from configuration: {config}''' ) lowerCamelCase : str = TaForConditionalGeneration(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_ta(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
48
1
"""simple docstring""" import argparse import os import re _A = 'src/transformers' # Pattern that looks at the indentation in a line. _A = re.compile(r'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. _A = re.compile(r'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _A = re.compile(r'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. _A = re.compile(r'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _A = re.compile(r'\[([^\]]+)\]') def UpperCAmelCase ( a_ ): '''simple docstring''' lowerCamelCase : Union[str, Any] = _re_indent.search(a_ ) return "" if search is None else search.groups()[0] def UpperCAmelCase ( a_, a_="", a_=None, a_=None ): '''simple docstring''' lowerCamelCase : str = 0 lowerCamelCase : List[Any] = code.split('\n' ) if start_prompt is not None: while not lines[index].startswith(a_ ): index += 1 lowerCamelCase : List[Any] = ['\n'.join(lines[:index] )] else: lowerCamelCase : str = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase : int = [lines[index]] index += 1 while index < len(a_ ) and (end_prompt is None or not lines[index].startswith(a_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(a_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ): current_block.append(lines[index] ) blocks.append('\n'.join(a_ ) ) if index < len(a_ ) - 1: lowerCamelCase : Union[str, Any] = [lines[index + 1]] index += 1 else: lowerCamelCase : Dict = [] else: blocks.append('\n'.join(a_ ) ) lowerCamelCase : Dict = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(a_ ) > 0: blocks.append('\n'.join(a_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(a_ ): blocks.append('\n'.join(lines[index:] ) ) return blocks def UpperCAmelCase ( a_ ): '''simple docstring''' def _inner(a_ ): return key(a_ ).lower().replace('_', '' ) return _inner def UpperCAmelCase ( a_, a_=None ): '''simple docstring''' def noop(a_ ): return x if key is None: lowerCamelCase : List[Any] = noop # Constants are all uppercase, they go first. lowerCamelCase : List[Any] = [obj for obj in objects if key(a_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase : List[str] = [obj for obj in objects if key(a_ )[0].isupper() and not key(a_ ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase : str = [obj for obj in objects if not key(a_ )[0].isupper()] lowerCamelCase : Optional[Any] = ignore_underscore(a_ ) return sorted(a_, key=a_ ) + sorted(a_, key=a_ ) + sorted(a_, key=a_ ) def UpperCAmelCase ( a_ ): '''simple docstring''' def _replace(a_ ): lowerCamelCase : Dict = match.groups()[0] if "," not in imports: return F"""[{imports}]""" lowerCamelCase : Optional[int] = [part.strip().replace('"', '' ) for part in imports.split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase : Any = keys[:-1] return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(a_ )] ) + "]" lowerCamelCase : int = import_statement.split('\n' ) if len(a_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase : int = 2 if lines[1].strip() == '[' else 1 lowerCamelCase : Union[str, Any] = [(i, _re_strip_line.search(a_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase : Tuple = sort_objects(a_, key=lambda a_ : x[1] ) lowerCamelCase : List[Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(a_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase : List[Any] = _re_bracket_content.sub(_replace, lines[1] ) else: lowerCamelCase : Any = [part.strip().replace('"', '' ) for part in lines[1].split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase : Dict = keys[:-1] lowerCamelCase : Dict = get_indent(lines[1] ) + ', '.join([F"""\"{k}\"""" for k in sort_objects(a_ )] ) return "\n".join(a_ ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase : Tuple = _re_bracket_content.sub(_replace, a_ ) return import_statement def UpperCAmelCase ( a_, a_=True ): '''simple docstring''' with open(a_, encoding='utf-8' ) as f: lowerCamelCase : Union[str, Any] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase : Any = split_code_in_indented_blocks( a_, start_prompt='_import_structure = {', end_prompt='if TYPE_CHECKING:' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1, len(a_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase : List[Any] = main_blocks[block_idx] lowerCamelCase : str = block.split('\n' ) # Get to the start of the imports. lowerCamelCase : int = 0 while line_idx < len(a_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase : Optional[int] = len(a_ ) else: line_idx += 1 if line_idx >= len(a_ ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase : Union[str, Any] = '\n'.join(block_lines[line_idx:-1] ) lowerCamelCase : Dict = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase : int = split_code_in_indented_blocks(a_, indent_level=a_ ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase : Union[str, Any] = _re_direct_key if '_import_structure = {' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase : Optional[int] = [(pattern.search(a_ ).groups()[0] if pattern.search(a_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase : List[Any] = [(i, key) for i, key in enumerate(a_ ) if key is not None] lowerCamelCase : Union[str, Any] = [x[0] for x in sorted(a_, key=lambda a_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase : Dict = 0 lowerCamelCase : str = [] for i in range(len(a_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowerCamelCase : Tuple = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(a_ ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase : Union[str, Any] = '\n'.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(a_ ): if check_only: return True else: print(F"""Overwriting {file}.""" ) with open(a_, 'w', encoding='utf-8' ) as f: f.write('\n'.join(a_ ) ) def UpperCAmelCase ( a_=True ): '''simple docstring''' lowerCamelCase : Tuple = [] for root, _, files in os.walk(a_ ): if "__init__.py" in files: lowerCamelCase : int = sort_imports(os.path.join(a_, '__init__.py' ), check_only=a_ ) if result: lowerCamelCase : Optional[Any] = [os.path.join(a_, '__init__.py' )] if len(a_ ) > 0: raise ValueError(F"""Would overwrite {len(a_ )} files, run `make style`.""" ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') _A = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
205
"""simple docstring""" import numpy as np def UpperCAmelCase ( a_, a_, a_ = 1E-12, a_ = 100, ): '''simple docstring''' assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) lowerCamelCase : Optional[int] = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_, input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. lowerCamelCase : Union[str, Any] = False lowerCamelCase : List[str] = 0 lowerCamelCase : Any = 0 lowerCamelCase : Dict = 1E12 while not convergence: # Multiple matrix by the vector. lowerCamelCase : Optional[int] = np.dot(a_, a_ ) # Normalize the resulting output vector. lowerCamelCase : Optional[int] = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) lowerCamelCase : Optional[Any] = vector.conj().T if is_complex else vector.T lowerCamelCase : str = np.dot(a_, np.dot(a_, a_ ) ) # Check convergence. lowerCamelCase : Optional[int] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: lowerCamelCase : int = True lowerCamelCase : Optional[Any] = lambda_ if is_complex: lowerCamelCase : Any = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ): '''simple docstring''' lowerCamelCase : str = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) lowerCamelCase : str = np.array([41, 4, 20] ) lowerCamelCase : Optional[Any] = real_input_matrix.astype(np.complexaaa ) lowerCamelCase : Dict = np.triu(1j * complex_input_matrix, 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T lowerCamelCase : List[Any] = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": lowerCamelCase : str = real_input_matrix lowerCamelCase : Any = real_vector elif problem_type == "complex": lowerCamelCase : str = complex_input_matrix lowerCamelCase : Dict = complex_vector # Our implementation. lowerCamelCase , lowerCamelCase : List[str] = power_iteration(a_, a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). lowerCamelCase , lowerCamelCase : Optional[Any] = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. lowerCamelCase : Dict = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. lowerCamelCase : List[str] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
205
1
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( _snake_case , unittest.TestCase ): '''simple docstring''' A_ : int = MgpstrTokenizer A_ : List[Any] = False A_ : int = {} A_ : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() # fmt: off _SCREAMING_SNAKE_CASE : Tuple = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on _SCREAMING_SNAKE_CASE : Dict = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) _SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__snake_case ) + """\n""" ) def UpperCAmelCase_ ( self , **__snake_case ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__snake_case ) def UpperCAmelCase_ ( self , __snake_case ): _SCREAMING_SNAKE_CASE : Dict = """tester""" _SCREAMING_SNAKE_CASE : Any = """tester""" return input_text, output_text @unittest.skip("""MGP-STR always lower cases letters.""" ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : str = self.get_tokenizers(do_lower_case=__snake_case ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): _SCREAMING_SNAKE_CASE : Any = """[SPECIAL_TOKEN]""" tokenizer.add_special_tokens({"""cls_token""": special_token} ) _SCREAMING_SNAKE_CASE : Dict = tokenizer.encode([special_token] , add_special_tokens=__snake_case ) self.assertEqual(len(__snake_case ) , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode(__snake_case , skip_special_tokens=__snake_case ) self.assertTrue(special_token not in decoded ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.get_input_output_texts(__snake_case ) _SCREAMING_SNAKE_CASE : int = tokenizer.tokenize(__snake_case ) _SCREAMING_SNAKE_CASE : List[str] = tokenizer.convert_tokens_to_ids(__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) _SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens(__snake_case ) self.assertNotEqual(len(__snake_case ) , 0 ) _SCREAMING_SNAKE_CASE : int = tokenizer.decode(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(text_a.replace(""" """ , """""" ) , __snake_case ) @unittest.skip("""MGP-STR tokenizer only handles one sequence.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""inputs cannot be pretokenized in MgpstrTokenizer""" ) def UpperCAmelCase_ ( self ): pass
200
'''simple docstring''' import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class lowercase__ : '''simple docstring''' def __init__( self , __snake_case , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case="resnet50" , __snake_case=3 , __snake_case=32 , __snake_case=3 , __snake_case=True , __snake_case=True , ): _SCREAMING_SNAKE_CASE : Tuple = parent _SCREAMING_SNAKE_CASE : Optional[int] = out_indices if out_indices is not None else [4] _SCREAMING_SNAKE_CASE : str = stage_names _SCREAMING_SNAKE_CASE : List[str] = out_features _SCREAMING_SNAKE_CASE : int = backbone _SCREAMING_SNAKE_CASE : Any = batch_size _SCREAMING_SNAKE_CASE : List[str] = image_size _SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels _SCREAMING_SNAKE_CASE : int = use_pretrained_backbone _SCREAMING_SNAKE_CASE : Optional[Any] = is_training def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE : List[Any] = self.get_config() return config, pixel_values def UpperCAmelCase_ ( self ): return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def UpperCAmelCase_ ( self , __snake_case , __snake_case ): _SCREAMING_SNAKE_CASE : Optional[int] = TimmBackbone(config=__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[Any] = model(__snake_case ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch @require_timm class lowercase__ ( _snake_case , _snake_case , _snake_case , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = (TimmBackbone,) if is_torch_available() else () A_ : Tuple = {"""feature-extraction""": TimmBackbone} if is_torch_available() else {} A_ : Optional[Any] = False A_ : List[Any] = False A_ : Dict = False A_ : int = False def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Any = TimmBackboneModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case ) def UpperCAmelCase_ ( self ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Optional[int] = """resnet18""" _SCREAMING_SNAKE_CASE : Tuple = """microsoft/resnet-18""" _SCREAMING_SNAKE_CASE : List[str] = AutoBackbone.from_pretrained(__snake_case , use_timm_backbone=__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = AutoBackbone.from_pretrained(__snake_case ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) _SCREAMING_SNAKE_CASE : Optional[Any] = AutoBackbone.from_pretrained(__snake_case , use_timm_backbone=__snake_case , out_indices=[1, 2, 3] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoBackbone.from_pretrained(__snake_case , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip("""TimmBackbone doesn't support feed forward chunking""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""TimmBackbone doesn't support output_attentions.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""Safetensors is not supported by timm.""" ) 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 ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[str] = model_class(__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : int = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : List[str] = self.has_attentions # no need to test all models as different heads yield the same functionality _SCREAMING_SNAKE_CASE : str = self.all_model_classes[0] _SCREAMING_SNAKE_CASE : str = model_class(__snake_case ) model.to(__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(__snake_case , __snake_case ) _SCREAMING_SNAKE_CASE : Tuple = model(**__snake_case ) _SCREAMING_SNAKE_CASE : Optional[Any] = outputs[0][-1] # Encoder-/Decoder-only models _SCREAMING_SNAKE_CASE : str = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: _SCREAMING_SNAKE_CASE : Optional[int] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=__snake_case ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : str = model_class(__snake_case ) model.to(__snake_case ) model.eval() _SCREAMING_SNAKE_CASE : List[str] = model(**__snake_case ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None _SCREAMING_SNAKE_CASE : Union[str, Any] = copy.deepcopy(__snake_case ) _SCREAMING_SNAKE_CASE : Optional[Any] = None _SCREAMING_SNAKE_CASE : Tuple = model_class(__snake_case ) model.to(__snake_case ) model.eval() _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__snake_case ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights _SCREAMING_SNAKE_CASE : str = copy.deepcopy(__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__snake_case ) model.to(__snake_case ) model.eval() _SCREAMING_SNAKE_CASE : List[Any] = model(**__snake_case )
200
1
def A (__A : str ) -> Dict: """simple docstring""" UpperCAmelCase_ = [int(lowerCAmelCase__ ) for i in ip_va_address.split('''.''' ) if i.isdigit()] return len(lowerCAmelCase__ ) == 4 and all(0 <= int(lowerCAmelCase__ ) <= 254 for octet in octets ) if __name__ == "__main__": snake_case_ : Optional[Any] = input().strip() snake_case_ : Optional[int] = "valid" if is_ip_va_address_valid(ip) else "invalid" print(f"{ip} is a {valid_or_invalid} IP v4 address.")
351
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __snake_case ( unittest.TestCase , a ): def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = load_tool('''text-to-speech''') self.tool.setup() def lowerCamelCase ( self : int): """simple docstring""" torch.manual_seed(0) UpperCAmelCase_ = self.tool('''hey''') UpperCAmelCase_ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5]) , )) def lowerCamelCase ( self : Any): """simple docstring""" torch.manual_seed(0) UpperCAmelCase_ = self.tool('''hey''') UpperCAmelCase_ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5]) , ))
7
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : Union[str, Any] = logging.get_logger(__name__) lowercase__ : List[Any] = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = 'fnet' def __init__( self , SCREAMING_SNAKE_CASE_=32000 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.0_2 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , )-> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = vocab_size __UpperCamelCase = max_position_embeddings __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = initializer_range __UpperCamelCase = type_vocab_size __UpperCamelCase = layer_norm_eps __UpperCamelCase = use_tpu_fourier_optimizations __UpperCamelCase = tpu_short_seq_length
328
from __future__ import annotations import math def A_ ( snake_case : int ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True lowercase__ : int = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def A_ ( snake_case : int ) -> list[int]: '''simple docstring''' if not isinstance(snake_case , snake_case ): raise ValueError('''n must be an integer''' ) if n <= 0: raise ValueError('''n must be >= 0''' ) __UpperCamelCase = [] for num in range(len(snake_case ) ): __UpperCamelCase = 0 while 2 * i * i <= odd_composites[num]: __UpperCamelCase = odd_composites[num] - 2 * i * i if is_prime(snake_case ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(snake_case ) == n: return list_nums return [] def A_ ( ) -> int: '''simple docstring''' return compute_nums(1 )[0] if __name__ == "__main__": print(F"{solution() = }")
328
1
def lowerCAmelCase_ (lowerCAmelCase__: int ): """simple docstring""" if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_: Tuple = F'Input value of [number={number}] must be an integer' raise TypeError(lowerCAmelCase__ ) if number < 0: return False UpperCAmelCase_: Dict = number * number while number > 0: if number % 1_0 != number_square % 1_0: return False number //= 1_0 number_square //= 1_0 return True if __name__ == "__main__": import doctest doctest.testmod()
82
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class _a : def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=10, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=32 * 8, SCREAMING_SNAKE_CASE_=32 * 8, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=64, ) -> Union[str, Any]: UpperCAmelCase_: int = parent UpperCAmelCase_: Tuple = batch_size UpperCAmelCase_: int = is_training UpperCAmelCase_: Any = use_auxiliary_loss UpperCAmelCase_: str = num_queries UpperCAmelCase_: List[Any] = num_channels UpperCAmelCase_: Union[str, Any] = min_size UpperCAmelCase_: Optional[Any] = max_size UpperCAmelCase_: Tuple = num_labels UpperCAmelCase_: Union[str, Any] = hidden_dim UpperCAmelCase_: int = hidden_dim def __snake_case (self ) -> Tuple: UpperCAmelCase_: List[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[str] = torch.ones([self.batch_size, self.min_size, self.max_size], device=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=SCREAMING_SNAKE_CASE_ ) > 0.5 ).float() UpperCAmelCase_: Optional[int] = (torch.rand((self.batch_size, self.num_labels), device=SCREAMING_SNAKE_CASE_ ) > 0.5).long() UpperCAmelCase_: Union[str, Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __snake_case (self ) -> Any: UpperCAmelCase_: Any = MaskaFormerConfig( hidden_size=self.hidden_dim, ) UpperCAmelCase_: Any = self.num_queries UpperCAmelCase_: Dict = self.num_labels UpperCAmelCase_: Dict = [1, 1, 1, 1] UpperCAmelCase_: int = self.num_channels UpperCAmelCase_: Union[str, Any] = 64 UpperCAmelCase_: List[Any] = 128 UpperCAmelCase_: Optional[Any] = self.hidden_dim UpperCAmelCase_: str = self.hidden_dim UpperCAmelCase_: List[str] = self.hidden_dim return config def __snake_case (self ) -> Union[str, Any]: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: Dict = self.prepare_config_and_inputs() UpperCAmelCase_: Any = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCAmelCase_: Union[str, Any] = output.encoder_hidden_states UpperCAmelCase_: int = output.pixel_decoder_hidden_states UpperCAmelCase_: Any = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), config.decoder_layers ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=False ) -> Optional[Any]: with torch.no_grad(): UpperCAmelCase_: Dict = MaskaFormerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCAmelCase_: List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: str = model(SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape, (self.batch_size, self.num_queries, self.hidden_dim), ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCAmelCase_: Tuple = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE_ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape, (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4), ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCAmelCase_: Dict = model(pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: int = model(SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Dict = model( pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape, torch.Size([1] ) ) @require_torch class _a ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): A = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () A = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} A = False A = False A = False A = False def __snake_case (self ) -> Any: UpperCAmelCase_: List[str] = MaskaFormerModelTester(self ) UpperCAmelCase_: Any = ConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, has_text_modality=SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> List[Any]: self.config_tester.run_common_tests() def __snake_case (self ) -> Optional[Any]: UpperCAmelCase_ , UpperCAmelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> Union[str, Any]: UpperCAmelCase_: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def __snake_case (self ) -> Dict: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def __snake_case (self ) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def __snake_case (self ) -> List[str]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def __snake_case (self ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def __snake_case (self ) -> List[str]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __snake_case (self ) -> Dict: pass def __snake_case (self ) -> Any: UpperCAmelCase_ , UpperCAmelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_: Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_: Tuple = [*signature.parameters.keys()] UpperCAmelCase_: str = ["""pixel_values"""] self.assertListEqual(arg_names[:1], SCREAMING_SNAKE_CASE_ ) @slow def __snake_case (self ) -> List[Any]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCAmelCase_: Any = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> Union[str, Any]: UpperCAmelCase_: str = (self.model_tester.min_size,) * 2 UpperCAmelCase_: str = { """pixel_values""": torch.randn((2, 3, *size), device=SCREAMING_SNAKE_CASE_ ), """mask_labels""": torch.randn((2, 10, *size), device=SCREAMING_SNAKE_CASE_ ), """class_labels""": torch.zeros(2, 10, device=SCREAMING_SNAKE_CASE_ ).long(), } UpperCAmelCase_: Dict = self.model_tester.get_config() UpperCAmelCase_: Optional[Any] = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[Any] = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None ) def __snake_case (self ) -> List[Any]: UpperCAmelCase_ , UpperCAmelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> List[Any]: UpperCAmelCase_ , UpperCAmelCase_: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_: List[Any] = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Any = model(**SCREAMING_SNAKE_CASE_, output_attentions=SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.attentions is not None ) def __snake_case (self ) -> Optional[int]: if not self.model_tester.is_training: return UpperCAmelCase_: Union[str, Any] = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: Any = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_: Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCAmelCase_: Optional[int] = model(SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ).loss loss.backward() def __snake_case (self ) -> Optional[Any]: UpperCAmelCase_: Any = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: List[Any] = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_: Union[str, Any] = True UpperCAmelCase_: str = True UpperCAmelCase_: Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCAmelCase_: Union[str, Any] = model(SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCAmelCase_: Union[str, Any] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCAmelCase_: Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCAmelCase_: Optional[Any] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) a : int = 1E-4 def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class _a ( unittest.TestCase ): @cached_property def __snake_case (self ) -> Optional[int]: return "facebook/mask2former-swin-small-coco-instance" @cached_property def __snake_case (self ) -> Dict: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __snake_case (self ) -> List[str]: UpperCAmelCase_: int = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[int] = self.default_image_processor UpperCAmelCase_: Optional[Any] = prepare_img() UpperCAmelCase_: str = image_processor(SCREAMING_SNAKE_CASE_, return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_, (1, 3, 384, 384) ) with torch.no_grad(): UpperCAmelCase_: Optional[int] = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Union[str, Any] = torch.tensor( [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) UpperCAmelCase_: Dict = torch.tensor( [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) UpperCAmelCase_: str = torch.tensor( [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) def __snake_case (self ) -> Optional[Any]: UpperCAmelCase_: Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase_: Tuple = self.default_image_processor UpperCAmelCase_: Dict = prepare_img() UpperCAmelCase_: Any = image_processor(SCREAMING_SNAKE_CASE_, return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_, (1, 3, 384, 384) ) with torch.no_grad(): UpperCAmelCase_: int = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits UpperCAmelCase_: int = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape, (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCAmelCase_: Optional[Any] = [ [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1], [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1], [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5], ] UpperCAmelCase_: int = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits UpperCAmelCase_: Dict = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape, (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCAmelCase_: Any = torch.tensor( [ [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2], [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3], [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) def __snake_case (self ) -> Tuple: UpperCAmelCase_: List[str] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase_: Dict = self.default_image_processor UpperCAmelCase_: str = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )], segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )], return_tensors="""pt""", ) UpperCAmelCase_: int = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[int] = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""mask_labels"""]] UpperCAmelCase_: int = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""class_labels"""]] with torch.no_grad(): UpperCAmelCase_: Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None )
82
1
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def lowerCamelCase__ ( __snake_case ) -> int: """simple docstring""" _UpperCamelCase = prime_factors(__snake_case ) if is_square_free(__snake_case ): return -1 if len(__snake_case ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
194
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin _a = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ): lowercase__ = SpeechTaTokenizer lowercase__ = False lowercase__ = True def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _UpperCamelCase = SpeechTaTokenizer(__a) _UpperCamelCase = AddedToken('''<mask>''' , lstrip=__a , rstrip=__a) _UpperCamelCase = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token}) tokenizer.add_tokens(['''<ctc_blank>''']) tokenizer.save_pretrained(self.tmpdirname) def UpperCAmelCase ( self , __a) -> List[str]: '''simple docstring''' _UpperCamelCase = '''this is a test''' _UpperCamelCase = '''this is a test''' return input_text, output_text def UpperCAmelCase ( self , __a , __a=False , __a=20 , __a=5) -> List[str]: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self.get_input_output_texts(__a) _UpperCamelCase = tokenizer.encode(__a , add_special_tokens=__a) _UpperCamelCase = tokenizer.decode(__a , clean_up_tokenization_spaces=__a) return text, ids def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = '''<pad>''' _UpperCamelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a) , __a) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a) , __a) def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-4] , '''œ''') self.assertEqual(vocab_keys[-2] , '''<mask>''') self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''') self.assertEqual(len(__a) , 81) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79) def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = self.get_tokenizers(do_lower_case=__a) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}'''): _UpperCamelCase = tokenizer.vocab_size _UpperCamelCase = len(__a) self.assertNotEqual(__a , 0) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) _UpperCamelCase = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] _UpperCamelCase = tokenizer.add_tokens(__a) _UpperCamelCase = tokenizer.vocab_size _UpperCamelCase = len(__a) self.assertNotEqual(__a , 0) self.assertEqual(__a , __a) self.assertEqual(__a , len(__a)) self.assertEqual(__a , all_size + len(__a)) _UpperCamelCase = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__a) self.assertGreaterEqual(len(__a) , 4) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) _UpperCamelCase = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} _UpperCamelCase = tokenizer.add_special_tokens(__a) _UpperCamelCase = tokenizer.vocab_size _UpperCamelCase = len(__a) self.assertNotEqual(__a , 0) self.assertEqual(__a , __a) self.assertEqual(__a , len(__a)) self.assertEqual(__a , all_size_a + len(__a)) _UpperCamelCase = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__a) self.assertGreaterEqual(len(__a) , 6) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[0] , tokens[1]) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokens[-4]) self.assertEqual(tokens[0] , tokenizer.eos_token_id) self.assertEqual(tokens[-3] , tokenizer.pad_token_id) def UpperCAmelCase ( self) -> Any: '''simple docstring''' pass def UpperCAmelCase ( self) -> int: '''simple docstring''' pass def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = tokenizer.tokenize('''This is a test''') # fmt: off self.assertListEqual(__a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t''']) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__a) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) _UpperCamelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( __a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.''']) _UpperCamelCase = tokenizer.convert_tokens_to_ids(__a) # fmt: off self.assertListEqual(__a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26]) # fmt: on _UpperCamelCase = tokenizer.convert_ids_to_tokens(__a) self.assertListEqual( __a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.''']) @slow def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' # Use custom sequence because this tokenizer does not handle numbers. _UpperCamelCase = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off _UpperCamelCase = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__a , )
194
1
'''simple docstring''' import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCamelCase ( __lowerCAmelCase , unittest.TestCase ): # TODO: is there an appropriate internal test set? snake_case_ = '''ssube/stable-diffusion-x4-upscaler-onnx''' def _lowerCamelCase ( self, lowercase_=0 ) -> List[str]: snake_case = floats_tensor((1, 3, 128, 128), rng=random.Random(lowercase_ ) ) snake_case = torch.manual_seed(lowercase_ ) snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _lowerCamelCase ( self ) -> List[str]: snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = self.get_dummy_inputs() snake_case = pipe(**lowercase_ ).images snake_case = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) snake_case = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def _lowerCamelCase ( self ) -> Tuple: snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider' ) snake_case = PNDMScheduler.from_config(pipe.scheduler.config, skip_prk_steps=lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = self.get_dummy_inputs() snake_case = pipe(**lowercase_ ).images snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case = np.array( [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _lowerCamelCase ( self ) -> Dict: snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider' ) snake_case = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = self.get_dummy_inputs() snake_case = pipe(**lowercase_ ).images snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case = np.array( [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _lowerCamelCase ( self ) -> str: snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider' ) snake_case = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = self.get_dummy_inputs() snake_case = pipe(**lowercase_ ).images snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _lowerCamelCase ( self ) -> Union[str, Any]: snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider' ) snake_case = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = self.get_dummy_inputs() snake_case = pipe(**lowercase_ ).images snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case = np.array( [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): @property def _lowerCamelCase ( self ) -> int: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _lowerCamelCase ( self ) -> Optional[Any]: snake_case = ort.SessionOptions() snake_case = False return options def _lowerCamelCase ( self ) -> List[Any]: snake_case = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) snake_case = init_image.resize((128, 128) ) # using the PNDM scheduler by default snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx', provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = 'A fantasy landscape, trending on artstation' snake_case = torch.manual_seed(0 ) snake_case = pipe( prompt=lowercase_, image=lowercase_, guidance_scale=7.5, num_inference_steps=10, generator=lowercase_, output_type='np', ) snake_case = output.images snake_case = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) snake_case = np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _lowerCamelCase ( self ) -> Optional[int]: snake_case = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) snake_case = init_image.resize((128, 128) ) snake_case = LMSDiscreteScheduler.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx', subfolder='scheduler' ) snake_case = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx', scheduler=lowercase_, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=lowercase_ ) snake_case = 'A fantasy landscape, trending on artstation' snake_case = torch.manual_seed(0 ) snake_case = pipe( prompt=lowercase_, image=lowercase_, guidance_scale=7.5, num_inference_steps=20, generator=lowercase_, output_type='np', ) snake_case = output.images snake_case = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) snake_case = np.array( [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
332
'''simple docstring''' import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset lowerCAmelCase_ = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) lowerCAmelCase_ = dataset.iloc[:, 1:2].values lowerCAmelCase_ = dataset.iloc[:, 2].values lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = train_test_split(X, y, test_size=0.2, random_state=0) lowerCAmelCase_ = PolynomialFeatures(degree=4) lowerCAmelCase_ = poly_reg.fit_transform(X) lowerCAmelCase_ = LinearRegression() pol_reg.fit(X_poly, y) def __magic_name__ ( ) -> Any: plt.scatter(A , A , color='red' ) plt.plot(A , pol_reg.predict(poly_reg.fit_transform(A ) ) , color='blue' ) plt.title('Truth or Bluff (Linear Regression)' ) plt.xlabel('Position level' ) plt.ylabel('Salary' ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
332
1
from ..utils import DummyObject, requires_backends class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Optional[Any] = ['''flax'''] def __init__( self : Tuple ,*SCREAMING_SNAKE_CASE__ : Any ,**SCREAMING_SNAKE_CASE__ : List[Any]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Dict ,*SCREAMING_SNAKE_CASE__ : Optional[int] ,**SCREAMING_SNAKE_CASE__ : Tuple): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Optional[int] ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : List[str] = ['''flax'''] def __init__( self : Tuple ,*SCREAMING_SNAKE_CASE__ : Any ,**SCREAMING_SNAKE_CASE__ : int): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Optional[int] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Tuple): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Union[str, Any] ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : List[Any]): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Optional[Any] = ['''flax'''] def __init__( self : Union[str, Any] ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : List[Any] ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : str): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : str ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : str): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Optional[int] = ['''flax'''] def __init__( self : Optional[int] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Optional[int]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Tuple ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : List[str]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : List[str] ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : List[Any] = ['''flax'''] def __init__( self : Optional[int] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : int ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : str ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : int): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Optional[Any] = ['''flax'''] def __init__( self : Tuple ,*SCREAMING_SNAKE_CASE__ : Any ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Any ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Any ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Optional[int]): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : List[str] = ['''flax'''] def __init__( self : str ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : str): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : str ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Dict): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : List[Any] ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Tuple = ['''flax'''] def __init__( self : List[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : List[str]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Any ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : int): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Any ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Tuple = ['''flax'''] def __init__( self : List[Any] ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Dict ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : int ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : int): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Dict = ['''flax'''] def __init__( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : str): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : List[Any] ,*SCREAMING_SNAKE_CASE__ : Optional[int] ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : Union[str, Any] = ['''flax'''] def __init__( self : Optional[int] ,*SCREAMING_SNAKE_CASE__ : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : List[str]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Any ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Dict ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : Dict): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : str = ['''flax'''] def __init__( self : Tuple ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : Optional[int]): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Optional[int] ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Tuple): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(cls ,['flax']) class A_ ( metaclass=lowerCamelCase__ ): _UpperCAmelCase : str = ['''flax'''] def __init__( self : Optional[int] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : str): requires_backends(self ,['flax']) @classmethod def lowerCAmelCase ( cls : Dict ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): requires_backends(cls ,['flax']) @classmethod def lowerCAmelCase ( cls : Tuple ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Any): requires_backends(cls ,['flax'])
73
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
0
"""simple docstring""" import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) lowerCAmelCase__ : List[Any] =logging.getLogger(__name__) @dataclass(frozen=__UpperCamelCase ) class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : str UpperCamelCase__ : str UpperCamelCase__ : Optional[str] = None UpperCamelCase__ : Optional[str] = None UpperCamelCase__ : Optional[str] = None @dataclass(frozen=__UpperCamelCase ) class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : List[int] UpperCamelCase__ : Optional[List[int]] = None UpperCamelCase__ : Optional[List[int]] = None UpperCamelCase__ : Optional[Union[int, float]] = None UpperCamelCase__ : Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class UpperCAmelCase_ ( __UpperCamelCase ): '''simple docstring''' UpperCamelCase__ : List[InputFeatures] def __init__( self , _A , _A , _A , _A = None , _A=False , _A = False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = hans_processors[task]() __SCREAMING_SNAKE_CASE = os.path.join( _A , 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train' , tokenizer.__class__.__name__ , str(_A ) , _A , ) , ) __SCREAMING_SNAKE_CASE = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) __SCREAMING_SNAKE_CASE = label_list[2], label_list[1] __SCREAMING_SNAKE_CASE = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __SCREAMING_SNAKE_CASE = cached_features_file + """.lock""" with FileLock(_A ): if os.path.exists(_A ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) __SCREAMING_SNAKE_CASE = torch.load(_A ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) __SCREAMING_SNAKE_CASE = ( processor.get_dev_examples(_A ) if evaluate else processor.get_train_examples(_A ) ) logger.info('Training examples: %s' , len(_A ) ) __SCREAMING_SNAKE_CASE = hans_convert_examples_to_features(_A , _A , _A , _A ) logger.info('Saving features into cached file %s' , _A ) torch.save(self.features , _A ) def __len__( self ): '''simple docstring''' return len(self.features ) def __getitem__( self , _A ): '''simple docstring''' return self.features[i] def _A ( self ): '''simple docstring''' return self.label_list if is_tf_available(): import tensorflow as tf class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : List[InputFeatures] def __init__( self , _A , _A , _A , _A = 128 , _A=False , _A = False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = hans_processors[task]() __SCREAMING_SNAKE_CASE = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) __SCREAMING_SNAKE_CASE = label_list[2], label_list[1] __SCREAMING_SNAKE_CASE = label_list __SCREAMING_SNAKE_CASE = processor.get_dev_examples(_A ) if evaluate else processor.get_train_examples(_A ) __SCREAMING_SNAKE_CASE = hans_convert_examples_to_features(_A , _A , _A , _A ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='convert examples to features' ): if ex_index % 10_000 == 0: logger.info('Writing example %d of %d' % (ex_index, len(_A )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) __SCREAMING_SNAKE_CASE = tf.data.Dataset.from_generator( _A , ( { 'example_id': tf.intaa, 'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa, }, tf.intaa, ) , ( { 'example_id': tf.TensorShape([] ), 'input_ids': tf.TensorShape([None, None] ), 'attention_mask': tf.TensorShape([None, None] ), 'token_type_ids': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def _A ( self ): '''simple docstring''' return self.dataset def __len__( self ): '''simple docstring''' return len(self.features ) def __getitem__( self , _A ): '''simple docstring''' return self.features[i] def _A ( self ): '''simple docstring''' return self.label_list class UpperCAmelCase_ ( __UpperCamelCase ): '''simple docstring''' def _A ( self , _A ): '''simple docstring''' return self._create_examples(self._read_tsv(os.path.join(_A , 'heuristics_train_set.txt' ) ) , 'train' ) def _A ( self , _A ): '''simple docstring''' return self._create_examples(self._read_tsv(os.path.join(_A , 'heuristics_evaluation_set.txt' ) ) , 'dev' ) def _A ( self ): '''simple docstring''' return ["contradiction", "entailment", "neutral"] def _A ( self , _A , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] for i, line in enumerate(_A ): if i == 0: continue __SCREAMING_SNAKE_CASE = """%s-%s""" % (set_type, line[0]) __SCREAMING_SNAKE_CASE = line[5] __SCREAMING_SNAKE_CASE = line[6] __SCREAMING_SNAKE_CASE = line[7][2:] if line[7].startswith('ex' ) else line[7] __SCREAMING_SNAKE_CASE = line[0] examples.append(InputExample(guid=_A , text_a=_A , text_b=_A , label=_A , pairID=_A ) ) return examples def __lowercase ( a__ , a__ , a__ , a__ , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = {label: i for i, label in enumerate(lowercase__ )} __SCREAMING_SNAKE_CASE = [] for ex_index, example in tqdm.tqdm(enumerate(lowercase__ ) , desc='convert examples to features' ): if ex_index % 1_00_00 == 0: logger.info('Writing example %d' % (ex_index) ) __SCREAMING_SNAKE_CASE = tokenizer( example.text_a , example.text_b , add_special_tokens=lowercase__ , max_length=lowercase__ , padding='max_length' , truncation=lowercase__ , return_overflowing_tokens=lowercase__ , ) __SCREAMING_SNAKE_CASE = label_map[example.label] if example.label in label_map else 0 __SCREAMING_SNAKE_CASE = int(example.pairID ) features.append(InputFeatures(**lowercase__ , label=lowercase__ , pairID=lowercase__ ) ) for i, example in enumerate(examples[:5] ): logger.info('*** Example ***' ) logger.info(f"""guid: {example}""" ) logger.info(f"""features: {features[i]}""" ) return features lowerCAmelCase__ : Optional[int] ={ '''hans''': 3, } lowerCAmelCase__ : Any ={ '''hans''': HansProcessor, }
356
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' def __init__( self , _A , _A , _A = None , _A = None , _A = False , **_A , ): '''simple docstring''' super().__init__(features=_A , cache_dir=_A , keep_in_memory=_A , **_A ) __SCREAMING_SNAKE_CASE = Sql( cache_dir=_A , features=_A , sql=_A , con=_A , **_A , ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , ) # Build dataset for splits __SCREAMING_SNAKE_CASE = self.builder.as_dataset( split='train' , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _A , _A , _A , _A = None , _A = None , **_A , ): '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(f"""num_proc {num_proc} must be an integer > 0.""" ) __SCREAMING_SNAKE_CASE = dataset __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = con __SCREAMING_SNAKE_CASE = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE __SCREAMING_SNAKE_CASE = num_proc __SCREAMING_SNAKE_CASE = to_sql_kwargs def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.to_sql_kwargs.pop('sql' , _A ) __SCREAMING_SNAKE_CASE = self.to_sql_kwargs.pop('con' , _A ) __SCREAMING_SNAKE_CASE = self.to_sql_kwargs.pop('index' , _A ) __SCREAMING_SNAKE_CASE = self._write(index=_A , **self.to_sql_kwargs ) return written def _A ( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = args __SCREAMING_SNAKE_CASE = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs __SCREAMING_SNAKE_CASE = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) __SCREAMING_SNAKE_CASE = batch.to_pandas() __SCREAMING_SNAKE_CASE = df.to_sql(self.name , self.con , index=_A , **_A ) return num_rows or len(_A ) def _A ( self , _A , **_A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += num_rows return written
118
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup lowerCamelCase_ : Optional[Any] = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _A ( lowercase = "mumbai" ): """simple docstring""" a =BeautifulSoup(requests.get(url + location ).content , '''html.parser''' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('''div''' , attrs={'''data-tn-component''': '''organicJob'''} ): a =job.find('''a''' , attrs={'''data-tn-element''': '''jobTitle'''} ).text.strip() a =job.find('''span''' , {'''class''': '''company'''} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("""Bangalore"""), 1): print(F'Job {i:>2} is {job[0]} at {job[1]}')
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def lowerCAmelCase__ ( a__: List[str] ) -> int: '''simple docstring''' _UpperCAmelCase = args.pruning_method _UpperCAmelCase = args.threshold _UpperCAmelCase = args.model_name_or_path.rstrip('/' ) _UpperCAmelCase = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) _UpperCAmelCase = torch.load(os.path.join(__a , 'pytorch_model.bin' ) ) _UpperCAmelCase = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: _UpperCAmelCase = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: _UpperCAmelCase = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: _UpperCAmelCase = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": _UpperCAmelCase = MagnitudeBinarizer.apply(inputs=__a , threshold=__a ) _UpperCAmelCase = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue _UpperCAmelCase = name[:-6] _UpperCAmelCase = model[F'''{prefix_}mask_scores'''] _UpperCAmelCase = TopKBinarizer.apply(__a , __a ) _UpperCAmelCase = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue _UpperCAmelCase = name[:-6] _UpperCAmelCase = model[F'''{prefix_}mask_scores'''] _UpperCAmelCase = ThresholdBinarizer.apply(__a , __a , __a ) _UpperCAmelCase = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue _UpperCAmelCase = name[:-6] _UpperCAmelCase = model[F'''{prefix_}mask_scores'''] _UpperCAmelCase = -0.1, 1.1 _UpperCAmelCase = torch.sigmoid(__a ) _UpperCAmelCase = s * (r - l) + l _UpperCAmelCase = s_bar.clamp(min=0.0 , max=1.0 ) _UpperCAmelCase = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError('Unknown pruning method' ) if target_model_path is None: _UpperCAmelCase = os.path.join( os.path.dirname(__a ) , F'''bertarized_{os.path.basename(__a )}''' ) if not os.path.isdir(__a ): shutil.copytree(__a , __a ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(__a , os.path.join(__a , 'pytorch_model.bin' ) ) print('\nPruned model saved! See you later!' ) if __name__ == "__main__": lowerCAmelCase__ :Dict = argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) lowerCAmelCase__ :str = parser.parse_args() main(args)
365
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :List[str] = { '''configuration_x_clip''': [ '''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XCLIPConfig''', '''XCLIPTextConfig''', '''XCLIPVisionConfig''', ], '''processing_x_clip''': ['''XCLIPProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Any = [ '''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XCLIPModel''', '''XCLIPPreTrainedModel''', '''XCLIPTextModel''', '''XCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys lowerCAmelCase__ :str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
185
0
"""simple docstring""" import requests from bsa import BeautifulSoup def a__ ( lowerCAmelCase = "https://www.worldometers.info/coronavirus" ) -> dict: UpperCAmelCase__ : Dict = BeautifulSoup(requests.get(lowerCAmelCase ).text , """html.parser""" ) UpperCAmelCase__ : Dict = soup.findAll("""h1""" ) UpperCAmelCase__ : Optional[Any] = soup.findAll("""div""" , {"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" , {"""class""": """panel-title"""} ) values += soup.findAll("""div""" , {"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(lowerCAmelCase , lowerCAmelCase )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
171
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) _A = { """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": 10_00, """block_out_channels""": [32, 64], """attention_head_dim""": 8, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 64, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 3, """num_class_embeds""": 10_00, """block_out_channels""": [1_92, 1_92 * 2, 1_92 * 3, 1_92 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 2_56, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": None, """block_out_channels""": [2_56, 2_56, 2_56 * 2, 2_56 * 2, 2_56 * 4, 2_56 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """default""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """num_train_timesteps""": 40, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 2_01, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 1_51, """sigma_min""": 0.002, """sigma_max""": 80.0, } def a__ ( lowerCAmelCase ) -> Tuple: if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("""boolean value expected""" ) def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ) -> List[str]: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] UpperCAmelCase__ : Optional[Any] = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] UpperCAmelCase__ : Union[str, Any] = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.skip_connection.weight"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=None ) -> Optional[int]: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.norm.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.norm.bias"""] UpperCAmelCase__ : Union[str, Any] = weight_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Optional[Any] = bias_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = weight_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Dict = weight_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase ) -> str: UpperCAmelCase__ : Optional[Any] = torch.load(lowerCAmelCase , map_location="""cpu""" ) UpperCAmelCase__ : List[Any] = {} UpperCAmelCase__ : List[Any] = checkpoint["""time_embed.0.weight"""] UpperCAmelCase__ : str = checkpoint["""time_embed.0.bias"""] UpperCAmelCase__ : List[str] = checkpoint["""time_embed.2.weight"""] UpperCAmelCase__ : Dict = checkpoint["""time_embed.2.bias"""] if unet_config["num_class_embeds"] is not None: UpperCAmelCase__ : Dict = checkpoint["""label_emb.weight"""] UpperCAmelCase__ : str = checkpoint["""input_blocks.0.0.weight"""] UpperCAmelCase__ : List[str] = checkpoint["""input_blocks.0.0.bias"""] UpperCAmelCase__ : List[str] = unet_config["""down_block_types"""] UpperCAmelCase__ : Tuple = unet_config["""layers_per_block"""] UpperCAmelCase__ : int = unet_config["""attention_head_dim"""] UpperCAmelCase__ : Union[str, Any] = unet_config["""block_out_channels"""] UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Union[str, Any] = channels_list[0] for i, layer_type in enumerate(lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = channels_list[i] UpperCAmelCase__ : int = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Tuple = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : List[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Optional[Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Any = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : int = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Dict = F"""down_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : int = F"""input_blocks.{current_layer}.1""" UpperCAmelCase__ : Union[str, Any] = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : Any = F"""down_blocks.{i}.downsamplers.0""" UpperCAmelCase__ : List[str] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Tuple = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 UpperCAmelCase__ : Tuple = current_channels # hardcoded the mid-block for now UpperCAmelCase__ : List[Any] = """mid_block.resnets.0""" UpperCAmelCase__ : str = """middle_block.0""" UpperCAmelCase__ : List[str] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[str] = """mid_block.attentions.0""" UpperCAmelCase__ : Any = """middle_block.1""" UpperCAmelCase__ : Optional[int] = convert_attention(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[Any] = """mid_block.resnets.1""" UpperCAmelCase__ : Tuple = """middle_block.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Dict = unet_config["""up_block_types"""] for i, layer_type in enumerate(lowerCAmelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : Tuple = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : Any = F"""output_blocks.{current_layer-1}.1""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Dict = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Any = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = F"""up_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : List[str] = F"""output_blocks.{current_layer}.1""" UpperCAmelCase__ : Dict = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : int = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : int = F"""output_blocks.{current_layer-1}.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = checkpoint["""out.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint["""out.0.bias"""] UpperCAmelCase__ : Tuple = checkpoint["""out.2.weight"""] UpperCAmelCase__ : Optional[Any] = checkpoint["""out.2.bias"""] return new_checkpoint if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""") parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model.""" ) parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""") _A = parser.parse_args() _A = strabool(args.class_cond) _A = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: _A = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: _A = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: _A = None _A = con_pt_to_diffuser(args.unet_path, unet_config) _A = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: _A = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: _A = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') _A = CMStochasticIterativeScheduler(**scheduler_config) _A = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
171
1
"""simple docstring""" import math def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : int = 0 , __lowerCamelCase : int = 0 ) -> list: _snake_case = end or len(__lowerCamelCase ) for i in range(__lowerCamelCase , __lowerCamelCase ): _snake_case = i _snake_case = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: _snake_case = array[temp_index - 1] temp_index -= 1 _snake_case = temp_index_value return array def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : int , __lowerCamelCase : int ) -> None: # Max Heap _snake_case = index _snake_case = 2 * index + 1 # Left Node _snake_case = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: _snake_case = left_index if right_index < heap_size and array[largest] < array[right_index]: _snake_case = right_index if largest != index: _snake_case , _snake_case = array[largest], array[index] heapify(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _UpperCAmelCase ( __lowerCamelCase : list ) -> list: _snake_case = len(__lowerCamelCase ) for i in range(n // 2 , -1 , -1 ): heapify(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) for i in range(n - 1 , 0 , -1 ): _snake_case , _snake_case = array[0], array[i] heapify(__lowerCamelCase , 0 , __lowerCamelCase ) return array def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ) -> int: if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ) -> int: _snake_case = low _snake_case = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i _snake_case , _snake_case = array[j], array[i] i += 1 def _UpperCAmelCase ( __lowerCamelCase : list ) -> list: if len(__lowerCamelCase ) == 0: return array _snake_case = 2 * math.ceil(math.loga(len(__lowerCamelCase ) ) ) _snake_case = 16 return intro_sort(__lowerCamelCase , 0 , len(__lowerCamelCase ) , __lowerCamelCase , __lowerCamelCase ) def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ) -> list: while end - start > size_threshold: if max_depth == 0: return heap_sort(__lowerCamelCase ) max_depth -= 1 _snake_case = median_of_a(__lowerCamelCase , __lowerCamelCase , start + ((end - start) // 2) + 1 , end - 1 ) _snake_case = partition(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) intro_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _snake_case = p return insertion_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ = input('Enter numbers separated by a comma : ').strip() UpperCAmelCase__ = [float(item) for item in user_input.split(',')] print(sort(unsorted))
40
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : def __init__( self : str , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple=13 , _lowerCamelCase : int=32 , _lowerCamelCase : List[str]=3 , _lowerCamelCase : List[str]=4 , _lowerCamelCase : Optional[int]=[10, 20, 30, 40] , _lowerCamelCase : Dict=[2, 2, 3, 2] , _lowerCamelCase : Dict=True , _lowerCamelCase : Tuple=True , _lowerCamelCase : Tuple=37 , _lowerCamelCase : Optional[Any]="gelu" , _lowerCamelCase : Optional[Any]=10 , _lowerCamelCase : Any=0.0_2 , _lowerCamelCase : Optional[Any]=["stage2", "stage3", "stage4"] , _lowerCamelCase : Any=[2, 3, 4] , _lowerCamelCase : Any=None , ): _snake_case = parent _snake_case = batch_size _snake_case = image_size _snake_case = num_channels _snake_case = num_stages _snake_case = hidden_sizes _snake_case = depths _snake_case = is_training _snake_case = use_labels _snake_case = intermediate_size _snake_case = hidden_act _snake_case = num_labels _snake_case = initializer_range _snake_case = out_features _snake_case = out_indices _snake_case = scope def lowercase ( self : Dict ): _snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.num_labels ) _snake_case = self.get_config() return config, pixel_values, labels def lowercase ( self : str ): return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowercase ( self : Tuple , _lowerCamelCase : Tuple , _lowerCamelCase : int , _lowerCamelCase : List[str] ): _snake_case = ConvNextVaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _snake_case = model(_lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowercase ( self : Dict , _lowerCamelCase : List[str] , _lowerCamelCase : Tuple , _lowerCamelCase : Union[str, Any] ): _snake_case = ConvNextVaForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _snake_case = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase ( self : Optional[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple ): _snake_case = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _snake_case = model(_lowerCamelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _snake_case = None _snake_case = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _snake_case = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowercase ( self : str ): _snake_case = self.prepare_config_and_inputs() _snake_case , _snake_case , _snake_case = config_and_inputs _snake_case = {'''pixel_values''': pixel_values} return config, inputs_dict def lowercase ( self : int ): _snake_case = self.prepare_config_and_inputs() _snake_case , _snake_case , _snake_case = config_and_inputs _snake_case = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class lowerCAmelCase__ ( A_ , A_ , unittest.TestCase ): __a = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __a = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __a = False __a = False __a = False __a = False __a = False def lowercase ( self : str ): _snake_case = ConvNextVaModelTester(self ) _snake_case = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def lowercase ( self : List[str] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase ( self : Dict ): return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def lowercase ( self : Dict ): pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def lowercase ( self : int ): pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def lowercase ( self : int ): pass def lowercase ( self : Union[str, Any] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_with_labels() _snake_case = True if model_class.__name__ in [ *get_values(_lowerCamelCase ), *get_values(_lowerCamelCase ), ]: continue _snake_case = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() _snake_case = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) _snake_case = model(**_lowerCamelCase ).loss loss.backward() def lowercase ( self : Dict ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_with_labels() _snake_case = False _snake_case = True if ( model_class.__name__ in [*get_values(_lowerCamelCase ), *get_values(_lowerCamelCase )] or not model_class.supports_gradient_checkpointing ): continue _snake_case = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.gradient_checkpointing_enable() model.train() _snake_case = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) _snake_case = model(**_lowerCamelCase ).loss loss.backward() def lowercase ( self : Optional[Any] ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = model_class(_lowerCamelCase ) _snake_case = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case = [*signature.parameters.keys()] _snake_case = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def lowercase ( self : Optional[Any] ): _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def lowercase ( self : Optional[int] ): def check_hidden_states_output(_lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] ): _snake_case = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): _snake_case = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) _snake_case = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _snake_case = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _snake_case = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def lowercase ( self : List[str] ): _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def lowercase ( self : str ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = ConvNextVaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _UpperCAmelCase ( ) -> Optional[Any]: _snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): @cached_property def lowercase ( self : List[Any] ): return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def lowercase ( self : Optional[Any] ): _snake_case = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_lowerCamelCase ) _snake_case = self.default_image_processor _snake_case = prepare_img() _snake_case = preprocessor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): _snake_case = model(**_lowerCamelCase ) # verify the logits _snake_case = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) _snake_case = torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
40
1
'''simple docstring''' def a ( __a = 100 ) -> int: '''simple docstring''' UpperCamelCase__ :int = (n * (n + 1) // 2) ** 2 UpperCamelCase__ :Union[str, Any] = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F"""{solution() = }""")
97
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def __UpperCamelCase ( _A : List[str] , _A : Union[str, Any] , _A : Any , _A : Optional[int] ) ->List[str]: """simple docstring""" lowerCamelCase_ =s.rsplit(_A , _A ) return new.join(_A ) def __UpperCamelCase ( _A : List[Any] ) ->Dict: """simple docstring""" # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def __UpperCamelCase ( _A : str ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ ={} lowerCamelCase_ =["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: lowerCamelCase_ =key.replace(f'{group_key}.' , f'{group_key}.group.' ) if "res_path" in key: lowerCamelCase_ =key.replace("""res_path.""" , """res_path.path.""" ) if key.endswith(""".w""" ): lowerCamelCase_ =rreplace(_A , """.w""" , """.weight""" , 1 ) if key.endswith(""".b""" ): lowerCamelCase_ =rreplace(_A , """.b""" , """.bias""" , 1 ) lowerCamelCase_ =value.float() return upgrade @torch.no_grad() def __UpperCamelCase ( _A : Optional[int] , _A : Union[str, Any] , _A : List[Any]=None , _A : Dict=True ) ->Optional[int]: """simple docstring""" from dall_e import Encoder lowerCamelCase_ =Encoder() if os.path.exists(_A ): lowerCamelCase_ =torch.load(_A ) else: lowerCamelCase_ =torch.hub.load_state_dict_from_url(_A ) if isinstance(_A , _A ): lowerCamelCase_ =ckpt.state_dict() encoder.load_state_dict(_A ) if config_path is not None: lowerCamelCase_ =FlavaImageCodebookConfig.from_pretrained(_A ) else: lowerCamelCase_ =FlavaImageCodebookConfig() lowerCamelCase_ =FlavaImageCodebook(_A ).eval() lowerCamelCase_ =encoder.state_dict() lowerCamelCase_ =upgrade_state_dict(_A ) hf_model.load_state_dict(_A ) lowerCamelCase_ =hf_model.state_dict() lowerCamelCase_ =count_parameters(_A ) lowerCamelCase_ =count_parameters(_A ) assert torch.allclose(_A , _A , atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(_A ) else: return hf_state_dict if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __A : List[Any] = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
154
0
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCAmelCase : '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 0 ) -> None: lowercase__ , lowercase__ : List[str] = row, column lowercase__ : Dict = [[default_value for c in range(__lowerCAmelCase )] for r in range(__lowerCAmelCase )] def __str__( self ) -> str: lowercase__ : Tuple = F"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier lowercase__ : str = 0 for row_vector in self.array: for obj in row_vector: lowercase__ : Tuple = max(__lowerCAmelCase , len(str(__lowerCAmelCase ) ) ) lowercase__ : int = F"""%{max_element_length}s""" # Make string and return def single_line(__lowerCAmelCase ) -> str: nonlocal string_format_identifier lowercase__ : int = '''[''' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__lowerCAmelCase ) for row_vector in self.array ) return s def __repr__( self ) -> str: return str(self ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> bool: if not (isinstance(__lowerCAmelCase , (list, tuple) ) and len(__lowerCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , __lowerCAmelCase ) -> Any: assert self.validate_indicies(__lowerCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self , __lowerCAmelCase , __lowerCAmelCase ) -> None: assert self.validate_indicies(__lowerCAmelCase ) lowercase__ : Any = value def __add__( self , __lowerCAmelCase ) -> Matrix: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) assert self.row == another.row and self.column == another.column # Add lowercase__ : Optional[int] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowercase__ : Any = self[r, c] + another[r, c] return result def __neg__( self ) -> Matrix: lowercase__ : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowercase__ : Any = -self[r, c] return result def __sub__( self , __lowerCAmelCase ) -> Matrix: return self + (-another) def __mul__( self , __lowerCAmelCase ) -> Matrix: if isinstance(__lowerCAmelCase , (int, float) ): # Scalar multiplication lowercase__ : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowercase__ : str = self[r, c] * another return result elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): # Matrix multiplication assert self.column == another.row lowercase__ : Tuple = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: lowercase__ : Union[str, Any] = F"""Unsupported type given for another ({type(__lowerCAmelCase )})""" raise TypeError(__lowerCAmelCase ) def _lowerCAmelCase( self ) -> Matrix: lowercase__ : Tuple = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): lowercase__ : int = self[r, c] return result def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase ) -> Any: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate lowercase__ : Optional[Any] = v.transpose() lowercase__ : List[Any] = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __UpperCamelCase ( ): # a^(-1) lowercase__ : Any = Matrix(3 , 3 , 0 ) for i in range(3 ): lowercase__ : int = 1 print(F"""a^(-1) is {ainv}""" ) # u, v lowercase__ : str = Matrix(3 , 1 , 0 ) lowercase__ , lowercase__ , lowercase__ : List[Any] = 1, 2, -3 lowercase__ : Optional[Any] = Matrix(3 , 1 , 0 ) lowercase__ , lowercase__ , lowercase__ : Union[str, Any] = 4, -2, 5 print(F"""u is {u}""" ) print(F"""v is {v}""" ) print(F"""uv^T is {u * v.transpose()}""" ) # Sherman Morrison print(F"""(a + uv^T)^(-1) is {ainv.sherman_morrison(UpperCAmelCase , UpperCAmelCase )}""" ) def __UpperCamelCase ( ): import doctest doctest.testmod() testa()
214
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=2 , __lowerCAmelCase=32 , __lowerCAmelCase=16 , __lowerCAmelCase=3 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=32 , __lowerCAmelCase=4 , __lowerCAmelCase=[0, 1, 2, 3] , __lowerCAmelCase=4 , __lowerCAmelCase=37 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.0_2 , __lowerCAmelCase=3 , __lowerCAmelCase=[1, 384, 24, 24] , __lowerCAmelCase=True , __lowerCAmelCase=None , ) -> Dict: lowercase__ : str = parent lowercase__ : List[Any] = batch_size lowercase__ : Dict = image_size lowercase__ : Tuple = patch_size lowercase__ : str = num_channels lowercase__ : Dict = is_training lowercase__ : Optional[int] = use_labels lowercase__ : List[Any] = hidden_size lowercase__ : int = num_hidden_layers lowercase__ : int = backbone_out_indices lowercase__ : List[str] = num_attention_heads lowercase__ : Union[str, Any] = intermediate_size lowercase__ : List[Any] = hidden_act lowercase__ : str = hidden_dropout_prob lowercase__ : Tuple = attention_probs_dropout_prob lowercase__ : List[Any] = initializer_range lowercase__ : Optional[int] = num_labels lowercase__ : Optional[int] = backbone_featmap_shape lowercase__ : int = scope lowercase__ : List[str] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) lowercase__ : List[str] = (image_size // patch_size) ** 2 lowercase__ : Tuple = num_patches + 1 def _lowerCAmelCase( self ) -> List[str]: lowercase__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : int = None if self.use_labels: lowercase__ : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowercase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def _lowerCAmelCase( self ) -> Union[str, Any]: lowercase__ : Optional[Any] = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__lowerCAmelCase , backbone_featmap_shape=self.backbone_featmap_shape , ) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: lowercase__ : Optional[int] = DPTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() lowercase__ : Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: lowercase__ : Union[str, Any] = self.num_labels lowercase__ : str = DPTForDepthEstimation(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() lowercase__ : List[str] = model(__lowerCAmelCase ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: lowercase__ : str = self.num_labels lowercase__ : Tuple = DPTForSemanticSegmentation(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() lowercase__ : Dict = model(__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _lowerCAmelCase( self ) -> Optional[int]: lowercase__ : List[str] = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Dict = config_and_inputs lowercase__ : Tuple = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( a__ , a__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () SCREAMING_SNAKE_CASE = ( { "depth-estimation": DPTForDepthEstimation, "feature-extraction": DPTModel, "image-segmentation": DPTForSemanticSegmentation, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False def _lowerCAmelCase( self ) -> Union[str, Any]: lowercase__ : str = DPTModelTester(self ) lowercase__ : int = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=37 ) def _lowerCAmelCase( self ) -> List[Any]: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def _lowerCAmelCase( self ) -> Tuple: pass def _lowerCAmelCase( self ) -> Optional[Any]: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : str = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def _lowerCAmelCase( self ) -> List[str]: lowercase__ , lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Dict = model_class(__lowerCAmelCase ) lowercase__ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Tuple = [*signature.parameters.keys()] lowercase__ : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def _lowerCAmelCase( self ) -> List[str]: lowercase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowerCAmelCase( self ) -> Union[str, Any]: lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__lowerCAmelCase ) def _lowerCAmelCase( self ) -> Dict: lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase ) def _lowerCAmelCase( self ) -> Union[str, Any]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Dict = True if model_class in get_values(__lowerCAmelCase ): continue lowercase__ : List[str] = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.train() lowercase__ : Tuple = self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase ) lowercase__ : str = model(**__lowerCAmelCase ).loss loss.backward() def _lowerCAmelCase( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Any = False lowercase__ : str = True if model_class in get_values(__lowerCAmelCase ) or not model_class.supports_gradient_checkpointing: continue lowercase__ : List[str] = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.gradient_checkpointing_enable() model.train() lowercase__ : str = self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase ) lowercase__ : List[Any] = model(**__lowerCAmelCase ).loss loss.backward() def _lowerCAmelCase( self ) -> List[Any]: lowercase__ , lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = _config_zero_init(__lowerCAmelCase ) for model_class in self.all_model_classes: lowercase__ : Dict = model_class(config=__lowerCAmelCase ) # Skip the check for the backbone lowercase__ : Union[str, Any] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": lowercase__ : List[Any] = [F"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _lowerCAmelCase( self ) -> List[str]: pass @slow def _lowerCAmelCase( self ) -> List[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: lowercase__ : Dict = DPTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def _lowerCAmelCase( self ) -> str: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[str] = '''add''' with self.assertRaises(__lowerCAmelCase ): lowercase__ : Tuple = DPTForDepthEstimation(__lowerCAmelCase ) def __UpperCamelCase ( ): lowercase__ : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase( self ) -> Any: lowercase__ : Optional[int] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) lowercase__ : List[Any] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(__lowerCAmelCase ) lowercase__ : Optional[Any] = prepare_img() lowercase__ : Optional[Any] = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): lowercase__ : Optional[Any] = model(**__lowerCAmelCase ) lowercase__ : str = outputs.predicted_depth # verify the predicted depth lowercase__ : Optional[Any] = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , __lowerCAmelCase ) lowercase__ : str = torch.tensor( [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , __lowerCAmelCase , atol=1E-4 ) )
214
1