code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: 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(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
def __UpperCamelCase ( _A : int = 1000 ) ->int: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ =1, 1 lowerCamelCase_ =2 while True: lowerCamelCase_ =0 lowerCamelCase_ =fa + fa lowerCamelCase_ , lowerCamelCase_ =fa, f index += 1 for _ in str(_A ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig __A : Dict = [ 'openmmlab/upernet-convnext-tiny', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring __A : int = 'UperNetConfig' class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = 1 , )-> None: super().__init__() lowerCamelCase_ =nn.Convad( in_channels=_SCREAMING_SNAKE_CASE , out_channels=_SCREAMING_SNAKE_CASE , kernel_size=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE , dilation=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =nn.BatchNormad(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =nn.ReLU() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> torch.Tensor: lowerCamelCase_ =self.conv(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.batch_norm(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.activation(_SCREAMING_SNAKE_CASE ) return output class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> None: super().__init__() lowerCamelCase_ =[ nn.AdaptiveAvgPoolad(_SCREAMING_SNAKE_CASE ), UperNetConvModule(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> torch.Tensor: lowerCamelCase_ =input for layer in self.layers: lowerCamelCase_ =layer(_SCREAMING_SNAKE_CASE ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> None: super().__init__() lowerCamelCase_ =pool_scales lowerCamelCase_ =align_corners lowerCamelCase_ =in_channels lowerCamelCase_ =channels lowerCamelCase_ =[] for i, pool_scale in enumerate(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =UperNetPyramidPoolingBlock(pool_scale=_SCREAMING_SNAKE_CASE , in_channels=_SCREAMING_SNAKE_CASE , channels=_SCREAMING_SNAKE_CASE ) self.blocks.append(_SCREAMING_SNAKE_CASE ) self.add_module(str(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[torch.Tensor]: lowerCamelCase_ =[] for ppm in self.blocks: lowerCamelCase_ =ppm(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =nn.functional.interpolate( _SCREAMING_SNAKE_CASE , size=x.size()[2:] , mode="""bilinear""" , align_corners=self.align_corners ) ppm_outs.append(_SCREAMING_SNAKE_CASE ) return ppm_outs class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: super().__init__() lowerCamelCase_ =config lowerCamelCase_ =config.pool_scales # e.g. (1, 2, 3, 6) lowerCamelCase_ =in_channels lowerCamelCase_ =config.hidden_size lowerCamelCase_ =False lowerCamelCase_ =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module lowerCamelCase_ =UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) lowerCamelCase_ =UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module lowerCamelCase_ =nn.ModuleList() lowerCamelCase_ =nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer lowerCamelCase_ =UperNetConvModule(_SCREAMING_SNAKE_CASE , self.channels , kernel_size=1 ) lowerCamelCase_ =UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(_SCREAMING_SNAKE_CASE ) self.fpn_convs.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def _snake_case ( self )-> List[str]: self.apply(self._init_weights ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Dict: if isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =inputs[-1] lowerCamelCase_ =[x] psp_outs.extend(self.psp_modules(_SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =torch.cat(_SCREAMING_SNAKE_CASE , dim=1 ) lowerCamelCase_ =self.bottleneck(_SCREAMING_SNAKE_CASE ) return output def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> torch.Tensor: # build laterals lowerCamelCase_ =[lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(_SCREAMING_SNAKE_CASE ) ) # build top-down path lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowerCamelCase_ =laterals[i - 1].shape[2:] lowerCamelCase_ =laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=_SCREAMING_SNAKE_CASE , mode="""bilinear""" , align_corners=self.align_corners ) # build outputs lowerCamelCase_ =[self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowerCamelCase_ =nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="""bilinear""" , align_corners=self.align_corners ) lowerCamelCase_ =torch.cat(_SCREAMING_SNAKE_CASE , dim=1 ) lowerCamelCase_ =self.fpn_bottleneck(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.classifier(_SCREAMING_SNAKE_CASE ) return output class _SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 3 , _SCREAMING_SNAKE_CASE = 1 )-> None: super().__init__() lowerCamelCase_ =config lowerCamelCase_ =config.auxiliary_in_channels lowerCamelCase_ =config.auxiliary_channels lowerCamelCase_ =config.auxiliary_num_convs lowerCamelCase_ =config.auxiliary_concat_input lowerCamelCase_ =in_index lowerCamelCase_ =(kernel_size // 2) * dilation lowerCamelCase_ =[] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , dilation=_SCREAMING_SNAKE_CASE ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , dilation=_SCREAMING_SNAKE_CASE ) ) if self.num_convs == 0: lowerCamelCase_ =nn.Identity() else: lowerCamelCase_ =nn.Sequential(*_SCREAMING_SNAKE_CASE ) if self.concat_input: lowerCamelCase_ =UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=_SCREAMING_SNAKE_CASE , padding=kernel_size // 2 ) lowerCamelCase_ =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def _snake_case ( self )-> str: self.apply(self._init_weights ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: if isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> torch.Tensor: # just take the relevant feature maps lowerCamelCase_ =encoder_hidden_states[self.in_index] lowerCamelCase_ =self.convs(_SCREAMING_SNAKE_CASE ) if self.concat_input: lowerCamelCase_ =self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) lowerCamelCase_ =self.classifier(_SCREAMING_SNAKE_CASE ) return output class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Tuple = UperNetConfig _UpperCamelCase:Tuple = "pixel_values" _UpperCamelCase:Tuple = True def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def _snake_case ( self )-> Union[str, Any]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Optional[int]: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =value __A : List[str] = R'\n Parameters:\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 config ([`UperNetConfig`]): 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 : List[Any] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , lowerCAmelCase__ , ) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE )-> Dict: super().__init__(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) lowerCamelCase_ =UperNetHead(_SCREAMING_SNAKE_CASE , in_channels=self.backbone.channels ) lowerCamelCase_ =UperNetFCNHead(_SCREAMING_SNAKE_CASE ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length""" ) ) @replace_return_docstrings(output_type=_SCREAMING_SNAKE_CASE , config_class=_CONFIG_FOR_DOC ) def _snake_case ( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , )-> Union[tuple, SemanticSegmenterOutput]: lowerCamelCase_ =return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ =output_attentions if output_attentions is not None else self.config.output_attentions lowerCamelCase_ =self.backbone.forward_with_filtered_kwargs( _SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.feature_maps lowerCamelCase_ =self.decode_head(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =nn.functional.interpolate(_SCREAMING_SNAKE_CASE , size=pixel_values.shape[2:] , mode="""bilinear""" , align_corners=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =None if self.auxiliary_head is not None: lowerCamelCase_ =self.auxiliary_head(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =nn.functional.interpolate( _SCREAMING_SNAKE_CASE , size=pixel_values.shape[2:] , mode="""bilinear""" , align_corners=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =None if labels is not None: if self.config.num_labels == 1: raise ValueError("""The number of labels should be greater than one""" ) else: # compute weighted loss lowerCamelCase_ =CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) lowerCamelCase_ =loss_fct(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =loss_fct(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: lowerCamelCase_ =(logits,) + outputs[1:] else: lowerCamelCase_ =(logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=_SCREAMING_SNAKE_CASE , logits=_SCREAMING_SNAKE_CASE , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
707
# 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 : List[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 ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =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 : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =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 ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:Dict = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Dict: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:Tuple = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Tuple: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:Tuple = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Dict: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Any: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:int = ["torch", "transformers", "onnx"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 30.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class _SCREAMING_SNAKE_CASE ( TensorFormatter[Mapping, "torch.Tensor", Mapping]): def __init__( self , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> List[str]: super().__init__(features=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch_tensor_kwargs import torch # noqa import torch at initialization def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: import torch if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and column: if all( isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(_SCREAMING_SNAKE_CASE ) return column def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Any: import torch if isinstance(_SCREAMING_SNAKE_CASE , (str, bytes, type(_SCREAMING_SNAKE_CASE )) ): return value elif isinstance(_SCREAMING_SNAKE_CASE , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() lowerCamelCase_ ={} if isinstance(_SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): lowerCamelCase_ ={"""dtype""": torch.intaa} elif isinstance(_SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): lowerCamelCase_ ={"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): lowerCamelCase_ =np.asarray(_SCREAMING_SNAKE_CASE ) return torch.tensor(_SCREAMING_SNAKE_CASE , **{**default_dtype, **self.torch_tensor_kwargs} ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: import torch # support for torch, tf, jax etc. if hasattr(_SCREAMING_SNAKE_CASE , """__array__""" ) and not isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): lowerCamelCase_ =data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) return self._tensorize(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return map_nested(self._recursive_tensorize , _SCREAMING_SNAKE_CASE , map_list=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Mapping: lowerCamelCase_ =self.numpy_arrow_extractor().extract_row(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.python_features_decoder.decode_row(_SCREAMING_SNAKE_CASE ) return self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> "torch.Tensor": lowerCamelCase_ =self.numpy_arrow_extractor().extract_column(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.python_features_decoder.decode_column(_SCREAMING_SNAKE_CASE , pa_table.column_names[0] ) lowerCamelCase_ =self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self._consolidate(_SCREAMING_SNAKE_CASE ) return column def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Mapping: lowerCamelCase_ =self.numpy_arrow_extractor().extract_batch(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.python_features_decoder.decode_batch(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for column_name in batch: lowerCamelCase_ =self._consolidate(batch[column_name] ) return batch
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Tuple = StableDiffusionPanoramaPipeline _UpperCamelCase:List[Any] = TEXT_TO_IMAGE_PARAMS _UpperCamelCase:Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS _UpperCamelCase:Any = TEXT_TO_IMAGE_IMAGE_PARAMS _UpperCamelCase:Dict = TEXT_TO_IMAGE_IMAGE_PARAMS def _snake_case ( self )-> str: torch.manual_seed(0 ) lowerCamelCase_ =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) lowerCamelCase_ =DDIMScheduler() torch.manual_seed(0 ) lowerCamelCase_ =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_ =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) lowerCamelCase_ =CLIPTextModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) lowerCamelCase_ ={ """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 )-> Any: lowerCamelCase_ =torch.manual_seed(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """prompt""": """a photo of the dolomites""", """generator""": generator, # Setting height and width to None to prevent OOMs on CPU. """height""": None, """width""": None, """num_inference_steps""": 1, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _snake_case ( self )-> str: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> Dict: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self )-> Optional[Any]: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def _snake_case ( self )-> List[str]: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ="""french fries""" lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =output.images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> Any: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE , view_batch_size=2 ) lowerCamelCase_ =output.images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> Dict: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" ) lowerCamelCase_ =StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> str: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , skip_prk_steps=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self , _SCREAMING_SNAKE_CASE=0 )-> List[str]: lowerCamelCase_ =torch.manual_seed(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """prompt""": """a photo of the dolomites""", """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ ="""stabilityai/stable-diffusion-2-base""" lowerCamelCase_ =DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) lowerCamelCase_ =StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_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_ =self.get_inputs() lowerCamelCase_ =pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) lowerCamelCase_ =np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def _snake_case ( self )-> Any: lowerCamelCase_ =StableDiffusionPanoramaPipeline.from_pretrained( """stabilityai/stable-diffusion-2-base""" , safety_checker=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =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_ =self.get_inputs() lowerCamelCase_ =pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) lowerCamelCase_ =np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =0 def callback_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: lowerCamelCase_ =True nonlocal number_of_steps number_of_steps += 1 if step == 1: lowerCamelCase_ =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) lowerCamelCase_ =latents[0, -3:, -3:, -1] lowerCamelCase_ =np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: lowerCamelCase_ =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) lowerCamelCase_ =latents[0, -3:, -3:, -1] lowerCamelCase_ =np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 lowerCamelCase_ =False lowerCamelCase_ ="""stabilityai/stable-diffusion-2-base""" lowerCamelCase_ =DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) lowerCamelCase_ =StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() lowerCamelCase_ =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 _snake_case ( self )-> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowerCamelCase_ ="""stabilityai/stable-diffusion-2-base""" lowerCamelCase_ =DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) lowerCamelCase_ =StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =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_ =self.get_inputs() lowerCamelCase_ =pipe(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def __UpperCamelCase ( _A : Optional[int] ) ->Dict: """simple docstring""" monkeypatch.setattr("""datasets.utils.deprecation_utils._emitted_deprecation_warnings""" , set() ) @pytest.fixture def __UpperCamelCase ( _A : Tuple ) ->List[str]: """simple docstring""" class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =metric_id class _SCREAMING_SNAKE_CASE : _UpperCamelCase:List[Any] = [MetricMock(lowerCAmelCase__) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def _snake_case ( self )-> Tuple: return self._metrics monkeypatch.setattr("""datasets.inspect.huggingface_hub""" , HfhMock() ) @pytest.mark.parametrize( """func, args""" , [(load_metric, ("""metrics/mse""",)), (list_metrics, ()), (inspect_metric, ("""metrics/mse""", """tmp_path"""))] ) def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] , _A : int , _A : str , _A : Optional[int] ) ->Optional[int]: """simple docstring""" if "tmp_path" in args: lowerCamelCase_ =tuple(arg if arg != """tmp_path""" else tmp_path for arg in args ) with pytest.warns(_A , match="""https://huggingface.co/docs/evaluate""" ): func(*_A )
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> Union[str, Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext'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] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
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, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Any = StableDiffusionInpaintPipeline _UpperCamelCase:int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _UpperCamelCase:int = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _UpperCamelCase:Union[str, Any] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _UpperCamelCase:Optional[Any] = frozenset([]) def _snake_case ( self )-> List[Any]: torch.manual_seed(0 ) lowerCamelCase_ =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =PNDMScheduler(skip_prk_steps=_SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) lowerCamelCase_ =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCamelCase_ =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) lowerCamelCase_ =CLIPTextModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) lowerCamelCase_ ={ """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 )-> str: # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched lowerCamelCase_ =floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ =Image.fromarray(np.uinta(_SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) lowerCamelCase_ =Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_SCREAMING_SNAKE_CASE ).startswith("""mps""" ): lowerCamelCase_ =torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ =torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ ="""cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =StableDiffusionInpaintPipeline(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sd_pipe(**_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ =np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self )-> List[Any]: lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) lowerCamelCase_ =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) lowerCamelCase_ ="""stabilityai/stable-diffusion-2-inpainting""" lowerCamelCase_ =StableDiffusionInpaintPipeline.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_ ="""Face of a yellow cat, high resolution, sitting on a park bench""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =pipe( prompt=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) lowerCamelCase_ =output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) lowerCamelCase_ =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) lowerCamelCase_ ="""stabilityai/stable-diffusion-2-inpainting""" lowerCamelCase_ =StableDiffusionInpaintPipeline.from_pretrained( _SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=_SCREAMING_SNAKE_CASE , ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() lowerCamelCase_ ="""Face of a yellow cat, high resolution, sitting on a park bench""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =pipe( prompt=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) lowerCamelCase_ =output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _snake_case ( self )-> Optional[int]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) lowerCamelCase_ ="""stabilityai/stable-diffusion-2-inpainting""" lowerCamelCase_ =PNDMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) lowerCamelCase_ =StableDiffusionInpaintPipeline.from_pretrained( _SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) 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_ ="""Face of a yellow cat, high resolution, sitting on a park bench""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =pipe( prompt=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) lowerCamelCase_ =torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.6_5 * 10**9
713
from typing import Dict, Iterable, List, Optional, 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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) 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. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: 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(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_plbart': ['PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PLBartConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['PLBartTokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'PLBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'PLBartForCausalLM', 'PLBartForConditionalGeneration', 'PLBartForSequenceClassification', 'PLBartModel', 'PLBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys __A : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Dict = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase:List[Any] = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase:Tuple = "document_qa" _UpperCamelCase:Union[str, Any] = AutoProcessor _UpperCamelCase:str = VisionEncoderDecoderModel _UpperCamelCase:List[str] = ["image", "text"] _UpperCamelCase:Tuple = ["text"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ ="""<s_docvqa><s_question>{user_input}</s_question><s_answer>""" lowerCamelCase_ =task_prompt.replace("""{user_input}""" , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.pre_processor.tokenizer( _SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_ids lowerCamelCase_ =self.pre_processor(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Any: return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_SCREAMING_SNAKE_CASE , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_SCREAMING_SNAKE_CASE , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_SCREAMING_SNAKE_CASE , ).sequences def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =self.pre_processor.batch_decode(_SCREAMING_SNAKE_CASE )[0] lowerCamelCase_ =sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) lowerCamelCase_ =sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) lowerCamelCase_ =re.sub(R"""<.*?>""" , """""" , _SCREAMING_SNAKE_CASE , count=1 ).strip() # remove first task start token lowerCamelCase_ =self.pre_processor.tokenajson(_SCREAMING_SNAKE_CASE ) return sequence["answer"]
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
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 FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> str: lowerCamelCase_ =tempfile.mkdtemp() lowerCamelCase_ =[ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """的""", """价""", """格""", """是""", """15""", """便""", """alex""", """##andra""", """,""", """。""", """-""", """t""", """shirt""", ] lowerCamelCase_ =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] ) ) lowerCamelCase_ ={ """do_resize""": True, """size""": {"""height""": 224, """width""": 224}, """do_center_crop""": True, """crop_size""": {"""height""": 18, """width""": 18}, """do_normalize""": True, """image_mean""": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], """image_std""": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], """do_convert_rgb""": True, } lowerCamelCase_ =os.path.join(self.tmpdirname , _SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> Tuple: return BertTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: return BertTokenizerFast.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> int: return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Dict: shutil.rmtree(self.tmpdirname ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] lowerCamelCase_ =[Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =self.get_rust_tokenizer() lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) lowerCamelCase_ =ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) lowerCamelCase_ =ChineseCLIPProcessor.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 , _SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , _SCREAMING_SNAKE_CASE ) 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 , _SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ =self.get_tokenizer(cls_token="""(CLS)""" , sep_token="""(SEP)""" ) lowerCamelCase_ =self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="""(CLS)""" , sep_token="""(SEP)""" , do_normalize=_SCREAMING_SNAKE_CASE ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.prepare_image_inputs() lowerCamelCase_ =image_processor(_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , 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 )-> List[str]: lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ="""Alexandra,T-shirt的价格是15便士。""" lowerCamelCase_ =processor(text=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =tokenizer(_SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self )-> Dict: lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ="""Alexandra,T-shirt的价格是15便士。""" lowerCamelCase_ =self.prepare_image_inputs() lowerCamelCase_ =processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) 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(_SCREAMING_SNAKE_CASE ): processor() def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCamelCase_ =processor.batch_decode(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =tokenizer.batch_decode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.get_image_processor() lowerCamelCase_ =self.get_tokenizer() lowerCamelCase_ =ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ="""Alexandra,T-shirt的价格是15便士。""" lowerCamelCase_ =self.prepare_image_inputs() lowerCamelCase_ =processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' from __future__ import annotations __A : List[str] = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __A : Optional[Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __UpperCamelCase ( _A : list[float] ) ->list[float]: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =len(_A ) for i in range(_A ): lowerCamelCase_ =-1 for j in range(i + 1 , _A ): if arr[i] < arr[j]: lowerCamelCase_ =arr[j] break result.append(_A ) return result def __UpperCamelCase ( _A : list[float] ) ->list[float]: """simple docstring""" lowerCamelCase_ =[] for i, outer in enumerate(_A ): lowerCamelCase_ =-1 for inner in arr[i + 1 :]: if outer < inner: lowerCamelCase_ =inner break result.append(_A ) return result def __UpperCamelCase ( _A : list[float] ) ->list[float]: """simple docstring""" lowerCamelCase_ =len(_A ) lowerCamelCase_ =[] lowerCamelCase_ =[-1] * arr_size for index in reversed(range(_A ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: lowerCamelCase_ =stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __A : Any = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.17.0.dev0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') __A : List[str] = logging.getLogger(__name__) @dataclass class _SCREAMING_SNAKE_CASE : _UpperCamelCase:Optional[str] = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."}) _UpperCamelCase:Optional[str] = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) _UpperCamelCase:int = field( default=10_24 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."}) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) _UpperCamelCase:Optional[int] = field( default=lowerCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) _UpperCamelCase:Optional[int] = field( default=lowerCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) _UpperCamelCase:Optional[int] = field( default=lowerCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "A csv or a json file containing the training data."}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "A csv or a json file containing the validation data."}) _UpperCamelCase:Optional[str] = field(default=lowerCAmelCase__ , metadata={"help": "A csv or a json file containing the test data."}) def _snake_case ( self )-> str: if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("""Need either a GLUE task, a training/validation file or a dataset name.""" ) else: lowerCamelCase_ =self.train_file.split(""".""" )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." lowerCamelCase_ =self.validation_file.split(""".""" )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class _SCREAMING_SNAKE_CASE : _UpperCamelCase:str = field( default=lowerCAmelCase__ , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) _UpperCamelCase:str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =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. lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =parser.parse_args_into_dataclasses() # 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 )] , ) lowerCamelCase_ =training_args.get_process_log_level() logger.setLevel(_A ) datasets.utils.logging.set_verbosity(_A ) transformers.utils.logging.set_verbosity(_A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. lowerCamelCase_ =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ =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.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase_ =load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. lowerCamelCase_ ={"""train""": data_args.train_file, """validation""": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: lowerCamelCase_ =data_args.train_file.split(""".""" )[-1] lowerCamelCase_ =data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." lowerCamelCase_ =data_args.test_file else: raise ValueError("""Need either a GLUE task or a test file for `do_predict`.""" ) for key in data_files.keys(): logger.info(f'load a local file for {key}: {data_files[key]}' ) if data_args.train_file.endswith(""".csv""" ): # Loading a dataset from local csv files lowerCamelCase_ =load_dataset("""csv""" , data_files=_A , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files lowerCamelCase_ =load_dataset("""json""" , data_files=_A , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels lowerCamelCase_ =raw_datasets["""train"""].features["""label"""].names lowerCamelCase_ =len(_A ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer lowerCamelCase_ =TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=_A , ) lowerCamelCase_ =BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: lowerCamelCase_ ="""max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch lowerCamelCase_ =False # Some models have set the order of the labels to use, so let's make sure we do use it. lowerCamelCase_ ={"""Refused""": 0, """Entailed""": 1} lowerCamelCase_ ={0: """Refused""", 1: """Entailed"""} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) lowerCamelCase_ =min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(_A : Optional[Any] ): # Tokenize the texts def _convert_table_text_to_pandas(_A : Any ): lowerCamelCase_ =[_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] lowerCamelCase_ =pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd lowerCamelCase_ =examples["""statement"""] lowerCamelCase_ =list(map(_convert_table_text_to_pandas , examples["""table_text"""] ) ) lowerCamelCase_ =tokenizer(_A , _A , padding=_A , max_length=_A , truncation=_A ) lowerCamelCase_ =examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): lowerCamelCase_ =raw_datasets.map( _A , batched=_A , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on dataset""" , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) lowerCamelCase_ =raw_datasets["""train"""] if data_args.max_train_samples is not None: lowerCamelCase_ =train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) lowerCamelCase_ =raw_datasets["""validation"""] if data_args.max_eval_samples is not None: lowerCamelCase_ =eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("""--do_predict requires a test dataset""" ) lowerCamelCase_ =raw_datasets["""test"""] if data_args.max_predict_samples is not None: lowerCamelCase_ =predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(_A ) ) , 3 ): logger.info(f'Sample {index} of the training set: {train_dataset[index]}.' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(_A : EvalPrediction ): lowerCamelCase_ =p.predictions[0] if isinstance(p.predictions , _A ) else p.predictions lowerCamelCase_ =np.argmax(_A , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: lowerCamelCase_ =default_data_collator elif training_args.fpaa: lowerCamelCase_ =DataCollatorWithPadding(_A , pad_to_multiple_of=8 ) else: lowerCamelCase_ =None # Initialize our Trainer lowerCamelCase_ =Trainer( model=_A , args=_A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=_A , tokenizer=_A , data_collator=_A , ) # Training if training_args.do_train: lowerCamelCase_ =None if training_args.resume_from_checkpoint is not None: lowerCamelCase_ =training_args.resume_from_checkpoint elif last_checkpoint is not None: lowerCamelCase_ =last_checkpoint lowerCamelCase_ =trainer.train(resume_from_checkpoint=_A ) lowerCamelCase_ =train_result.metrics lowerCamelCase_ =( data_args.max_train_samples if data_args.max_train_samples is not None else len(_A ) ) lowerCamelCase_ =min(_A , len(_A ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , _A ) trainer.save_metrics("""train""" , _A ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) lowerCamelCase_ =trainer.evaluate(eval_dataset=_A ) lowerCamelCase_ =data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_A ) lowerCamelCase_ =min(_A , len(_A ) ) trainer.log_metrics("""eval""" , _A ) trainer.save_metrics("""eval""" , _A ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. lowerCamelCase_ =predict_dataset.remove_columns("""label""" ) lowerCamelCase_ =trainer.predict(_A , metric_key_prefix="""predict""" ).predictions lowerCamelCase_ =np.argmax(_A , axis=1 ) lowerCamelCase_ =os.path.join(training_args.output_dir , """predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(_A , """w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(_A ): lowerCamelCase_ =label_list[item] writer.write(f'{index}\t{item}\n' ) lowerCamelCase_ ={"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**_A ) else: trainer.create_model_card(**_A ) def __UpperCamelCase ( _A : List[str] ) ->Union[str, Any]: """simple docstring""" main() if __name__ == "__main__": main()
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def _snake_case ( self )-> Any: lowerCamelCase_ =self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """neck_hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """num_attention_heads""" ) ) class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=640 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE="silu" , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=None , )-> Any: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =last_hidden_size lowerCamelCase_ =num_attention_heads lowerCamelCase_ =hidden_act lowerCamelCase_ =conv_kernel_size lowerCamelCase_ =output_stride lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =use_labels lowerCamelCase_ =is_training lowerCamelCase_ =num_labels lowerCamelCase_ =initializer_range lowerCamelCase_ =scope def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase_ =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels, pixel_labels def _snake_case ( self )-> List[str]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =MobileViTModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =self.num_labels lowerCamelCase_ =MobileViTForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =self.num_labels lowerCamelCase_ =MobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Union[str, Any] = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) _UpperCamelCase:List[Any] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) _UpperCamelCase:List[str] = False _UpperCamelCase:Union[str, Any] = False _UpperCamelCase:List[Any] = False _UpperCamelCase:Optional[int] = False def _snake_case ( self )-> Any: lowerCamelCase_ =MobileViTModelTester(self ) lowerCamelCase_ =MobileViTConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViT does not use inputs_embeds""" ) def _snake_case ( self )-> int: pass @unittest.skip(reason="""MobileViT does not support input and output embeddings""" ) def _snake_case ( self )-> Dict: pass @unittest.skip(reason="""MobileViT does not output attentions""" ) def _snake_case ( self )-> Tuple: pass def _snake_case ( self )-> List[str]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> Optional[int]: pass def _snake_case ( self )-> str: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.hidden_states lowerCamelCase_ =5 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase_ =2 for i in range(len(_SCREAMING_SNAKE_CASE ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> Optional[Any]: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =MobileViTModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->int: """simple docstring""" lowerCamelCase_ =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @cached_property def _snake_case ( self )-> List[str]: return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None @slow def _snake_case ( self )-> str: lowerCamelCase_ =MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) # verify the logits lowerCamelCase_ =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def _snake_case ( self )-> str: lowerCamelCase_ =MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase_ =model.to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.logits # verify the logits lowerCamelCase_ =torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [ [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9_8_6_8, -9.7_1_3_2], [-11.0405, -11.0221, -10.7318]], [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]], ] , device=_SCREAMING_SNAKE_CASE , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase_ =model.to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.logits.detach().cpu() lowerCamelCase_ =image_processor.post_process_semantic_segmentation(outputs=_SCREAMING_SNAKE_CASE , target_sizes=[(50, 60)] ) lowerCamelCase_ =torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =image_processor.post_process_semantic_segmentation(outputs=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _SCREAMING_SNAKE_CASE )
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:int = LayoutLMTokenizer _UpperCamelCase:int = LayoutLMTokenizerFast _UpperCamelCase:List[str] = True _UpperCamelCase:Union[str, Any] = True def _snake_case ( self )-> Tuple: super().setUp() lowerCamelCase_ =[ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] lowerCamelCase_ =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> List[str]: return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ ="""UNwant\u00E9d,running""" lowerCamelCase_ ="""unwanted, running""" return input_text, output_text def _snake_case ( self )-> Any: lowerCamelCase_ =self.tokenizer_class(self.vocab_file ) lowerCamelCase_ =tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_SCREAMING_SNAKE_CASE , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [7, 4, 5, 10, 8, 9] ) def _snake_case ( self )-> int: pass
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
import math def __UpperCamelCase ( _A : float , _A : float ) ->float: """simple docstring""" if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("""In Malus Law, the angle is in the range 0-360 degrees""" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(_A ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='malus_law')
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
import string def __UpperCamelCase ( _A : str ) ->None: """simple docstring""" for key in range(len(string.ascii_uppercase ) ): lowerCamelCase_ ="""""" for symbol in message: if symbol in string.ascii_uppercase: lowerCamelCase_ =string.ascii_uppercase.find(_A ) lowerCamelCase_ =num - key if num < 0: lowerCamelCase_ =num + len(string.ascii_uppercase ) lowerCamelCase_ =translated + string.ascii_uppercase[num] else: lowerCamelCase_ =translated + symbol print(f'Decryption using Key #{key}: {translated}' ) def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =input("""Encrypted message: """ ) lowerCamelCase_ =message.upper() decrypt(_A ) if __name__ == "__main__": import doctest doctest.testmod() main()
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed __A : Any = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) __A : int = 'sshleifer/student_marian_en_ro_6_1' __A : Dict = 'sshleifer/tiny-mbart' @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def _snake_case ( self , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , )-> Tuple: lowerCamelCase_ =self.run_trainer( eval_steps=1 , max_len=12 , model_name=_SCREAMING_SNAKE_CASE , num_train_epochs=1 , distributed=_SCREAMING_SNAKE_CASE , extra_args_str=_SCREAMING_SNAKE_CASE , predict_with_generate=_SCREAMING_SNAKE_CASE , do_train=_SCREAMING_SNAKE_CASE , do_eval=_SCREAMING_SNAKE_CASE , do_predict=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =TrainerState.load_from_json(os.path.join(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history if not do_eval: return lowerCamelCase_ =[log for log in logs if """eval_loss""" in log.keys()] lowerCamelCase_ =eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats lowerCamelCase_ =eval_metrics[-1] assert isinstance(last_step_stats["""eval_bleu"""] , _SCREAMING_SNAKE_CASE ) assert not math.isnan(float(last_step_stats["""eval_loss"""] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _snake_case ( self )-> Optional[int]: self.run_seqaseq_quick() @require_torch_multi_gpu def _snake_case ( self )-> Optional[Any]: self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE ) @require_torch_multi_gpu def _snake_case ( self )-> List[str]: self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _snake_case ( self )-> Dict: self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp simple""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _snake_case ( self )-> List[str]: self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp simple --fp16""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _snake_case ( self )-> List[Any]: self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp zero_dp_2""" , predict_with_generate=_SCREAMING_SNAKE_CASE ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _snake_case ( self )-> Optional[Any]: self.run_seqaseq_quick( distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp zero_dp_2 --fp16""" , predict_with_generate=_SCREAMING_SNAKE_CASE ) @require_apex @require_torch_gpu def _snake_case ( self )-> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--fp16 --fp16_backend=apex""" ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--fp16 --fp16_backend=apex""" ) @parameterized.expand(["""base""", """low""", """high""", """mixed"""] ) @require_torch_multi_gpu def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Dict: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout lowerCamelCase_ ={ # test with the default log_level - should be info and thus log info once """base""": {"""extra_args_str""": """""", """n_matches""": 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes """low""": {"""extra_args_str""": """--log_level debug --log_level_replica debug""", """n_matches""": 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica """high""": {"""extra_args_str""": """--log_level error --log_level_replica debug""", """n_matches""": 1}, # test with high log_level and log_level_replica - should be quiet on all processes """mixed""": {"""extra_args_str""": """--log_level error --log_level_replica error""", """n_matches""": 0}, } lowerCamelCase_ =experiments[experiment_id] lowerCamelCase_ ={"""distributed""": True, """predict_with_generate""": False, """do_eval""": False, """do_predict""": False} lowerCamelCase_ ="""Running training""" with CaptureStderr() as cl: self.run_seqaseq_quick(**_SCREAMING_SNAKE_CASE , extra_args_str=data["""extra_args_str"""] ) lowerCamelCase_ =len(re.findall(_SCREAMING_SNAKE_CASE , cl.err ) ) self.assertEqual(_SCREAMING_SNAKE_CASE , data["""n_matches"""] ) @slow def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =self.run_trainer( eval_steps=2 , max_len=128 , model_name=_SCREAMING_SNAKE_CASE , learning_rate=3E-4 , num_train_epochs=10 , distributed=_SCREAMING_SNAKE_CASE , ) # Check metrics lowerCamelCase_ =TrainerState.load_from_json(os.path.join(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history lowerCamelCase_ =[log for log in logs if """eval_loss""" in log.keys()] lowerCamelCase_ =eval_metrics[0] lowerCamelCase_ =eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats["""eval_bleu"""] , _SCREAMING_SNAKE_CASE ) # test if do_predict saves generations and metrics lowerCamelCase_ =os.listdir(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={os.path.basename(_SCREAMING_SNAKE_CASE ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _snake_case ( self )-> Optional[Any]: from transformers.training_args import OptimizerNames def train_and_return_metrics(_SCREAMING_SNAKE_CASE ) -> Tuple[int, float]: lowerCamelCase_ ="""--skip_memory_metrics 0""" lowerCamelCase_ =self.run_trainer( max_len=128 , model_name=_SCREAMING_SNAKE_CASE , learning_rate=3E-4 , num_train_epochs=1 , optim=_SCREAMING_SNAKE_CASE , distributed=_SCREAMING_SNAKE_CASE , extra_args_str=_SCREAMING_SNAKE_CASE , do_eval=_SCREAMING_SNAKE_CASE , do_predict=_SCREAMING_SNAKE_CASE , n_gpus_to_use=1 , ) # Check metrics lowerCamelCase_ =TrainerState.load_from_json(Path(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history lowerCamelCase_ =int(logs[0]["""train_mem_gpu_peaked_delta"""] / 2**20 ) lowerCamelCase_ =int(logs[0]["""train_mem_gpu_alloc_delta"""] / 2**20 ) lowerCamelCase_ =logs[0]["""train_loss"""] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) lowerCamelCase_ =gpu_alloc_mem_orig - gpu_alloc_mem_bnb lowerCamelCase_ =gpu_peak_mem_orig + gpu_alloc_mem_orig lowerCamelCase_ =gpu_peak_mem_bnb + gpu_alloc_mem_bnb lowerCamelCase_ =gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings lowerCamelCase_ =120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got""" f' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' f' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' , ) self.assertGreater( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """should use ~150MB less total gpu memory with BNB, compared to without it for this model but got""" f' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' f' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' , ) self.assertEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 3E-3 , _SCREAMING_SNAKE_CASE = "adafactor" , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , )-> List[str]: lowerCamelCase_ =self.test_file_dir / """../fixtures/tests_samples/wmt_en_ro""" lowerCamelCase_ =self.get_auto_remove_tmp_dir() lowerCamelCase_ =f'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(_SCREAMING_SNAKE_CASE )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(_SCREAMING_SNAKE_CASE )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() lowerCamelCase_ =f'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(_SCREAMING_SNAKE_CASE )}\n '.split() lowerCamelCase_ =""" --do_predict """.split() lowerCamelCase_ =[] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: lowerCamelCase_ =get_gpu_count() lowerCamelCase_ =get_torch_dist_unique_port() lowerCamelCase_ =f'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() lowerCamelCase_ =[sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(_SCREAMING_SNAKE_CASE , env=self.get_env() ) else: lowerCamelCase_ =["""run_translation.py"""] + args with patch.object(_SCREAMING_SNAKE_CASE , """argv""" , _SCREAMING_SNAKE_CASE ): main() return output_dir
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[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_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[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 : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[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_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =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_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[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_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[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_ =keys[:-1] lowerCamelCase_ =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_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =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_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_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_ =[(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_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[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_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[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 : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0
def __UpperCamelCase ( _A : int , _A : float , _A : float ) ->float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def __UpperCamelCase ( _A : float , _A : float , _A : float ) ->float: """simple docstring""" return round(float((moles * 0.0_8_2_1 * temperature) / (volume) ) ) def __UpperCamelCase ( _A : float , _A : float , _A : float ) ->float: """simple docstring""" return round(float((moles * 0.0_8_2_1 * temperature) / (pressure) ) ) def __UpperCamelCase ( _A : float , _A : float , _A : float ) ->float: """simple docstring""" return round(float((pressure * volume) / (0.0_8_2_1 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: 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(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
import math def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =input("""Enter message: """ ) lowerCamelCase_ =int(input(f'Enter key [2-{len(_A ) - 1}]: ' ) ) lowerCamelCase_ =input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): lowerCamelCase_ =encrypt_message(_A , _A ) elif mode.lower().startswith("""d""" ): lowerCamelCase_ =decrypt_message(_A , _A ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f'Output:\n{text + "|"}' ) def __UpperCamelCase ( _A : int , _A : str ) ->str: """simple docstring""" lowerCamelCase_ =[""""""] * key for col in range(_A ): lowerCamelCase_ =col while pointer < len(_A ): cipher_text[col] += message[pointer] pointer += key return "".join(_A ) def __UpperCamelCase ( _A : int , _A : str ) ->str: """simple docstring""" lowerCamelCase_ =math.ceil(len(_A ) / key ) lowerCamelCase_ =key lowerCamelCase_ =(num_cols * num_rows) - len(_A ) lowerCamelCase_ =[""""""] * num_cols lowerCamelCase_ =0 lowerCamelCase_ =0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowerCamelCase_ =0 row += 1 return "".join(_A ) if __name__ == "__main__": import doctest doctest.testmod() main()
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __A : int = logging.get_logger(__name__) __A : Dict = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart __A : Optional[int] = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } __A : Tuple = { 'facebook/bart-base': 10_24, 'facebook/bart-large': 10_24, 'facebook/bart-large-mnli': 10_24, 'facebook/bart-large-cnn': 10_24, 'facebook/bart-large-xsum': 10_24, 'yjernite/bart_eli5': 10_24, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[int] = VOCAB_FILES_NAMES _UpperCamelCase:str = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase:Any = ["input_ids", "attention_mask"] _UpperCamelCase:Union[str, Any] = BartTokenizer def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="replace" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , )-> Any: super().__init__( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , errors=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , _SCREAMING_SNAKE_CASE ) != add_prefix_space: lowerCamelCase_ =getattr(_SCREAMING_SNAKE_CASE , pre_tok_state.pop("""type""" ) ) lowerCamelCase_ =add_prefix_space lowerCamelCase_ =pre_tok_class(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` lowerCamelCase_ ="""post_processor""" lowerCamelCase_ =getattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if tokenizer_component_instance: lowerCamelCase_ =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: lowerCamelCase_ =tuple(state["""sep"""] ) if "cls" in state: lowerCamelCase_ =tuple(state["""cls"""] ) lowerCamelCase_ =False if state.get("""add_prefix_space""" , _SCREAMING_SNAKE_CASE ) != add_prefix_space: lowerCamelCase_ =add_prefix_space lowerCamelCase_ =True if state.get("""trim_offsets""" , _SCREAMING_SNAKE_CASE ) != trim_offsets: lowerCamelCase_ =trim_offsets lowerCamelCase_ =True if changes_to_apply: lowerCamelCase_ =getattr(_SCREAMING_SNAKE_CASE , state.pop("""type""" ) ) lowerCamelCase_ =component_class(**_SCREAMING_SNAKE_CASE ) setattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> str: if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else value lowerCamelCase_ =value def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> BatchEncoding: lowerCamelCase_ =kwargs.get("""is_split_into_words""" , _SCREAMING_SNAKE_CASE ) 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(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> BatchEncoding: lowerCamelCase_ =kwargs.get("""is_split_into_words""" , _SCREAMING_SNAKE_CASE ) 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(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: lowerCamelCase_ =self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE ) return tuple(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> str: lowerCamelCase_ =[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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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]
707
# 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 : List[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 ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =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 : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =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 ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''simple docstring''' from __future__ import annotations from collections import deque class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =[] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(_SCREAMING_SNAKE_CASE ) self.set_fail_transitions() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> None: lowerCamelCase_ =0 for character in keyword: lowerCamelCase_ =self.find_next_state(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) lowerCamelCase_ =len(self.adlist ) - 1 else: lowerCamelCase_ =next_state self.adlist[current_state]["output"].append(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> None: lowerCamelCase_ =deque() for node in self.adlist[0]["next_states"]: q.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =0 while q: lowerCamelCase_ =q.popleft() for child in self.adlist[r]["next_states"]: q.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.adlist[r]["""fail_state"""] while ( self.find_next_state(_SCREAMING_SNAKE_CASE , self.adlist[child]["""value"""] ) is None and state != 0 ): lowerCamelCase_ =self.adlist[state]["""fail_state"""] lowerCamelCase_ =self.find_next_state( _SCREAMING_SNAKE_CASE , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: lowerCamelCase_ =0 lowerCamelCase_ =( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> dict[str, list[int]]: lowerCamelCase_ ={} # returns a dict with keywords and list of its occurrences lowerCamelCase_ =0 for i in range(len(_SCREAMING_SNAKE_CASE ) ): while ( self.find_next_state(_SCREAMING_SNAKE_CASE , string[i] ) is None and current_state != 0 ): lowerCamelCase_ =self.adlist[current_state]["""fail_state"""] lowerCamelCase_ =self.find_next_state(_SCREAMING_SNAKE_CASE , string[i] ) if next_state is None: lowerCamelCase_ =0 else: lowerCamelCase_ =next_state for key in self.adlist[current_state]["output"]: if key not in result: lowerCamelCase_ =[] result[key].append(i - len(_SCREAMING_SNAKE_CASE ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : List[Any] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Tuple = "ctrl" _UpperCamelCase:Union[str, Any] = ["past_key_values"] _UpperCamelCase:Union[str, Any] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , _SCREAMING_SNAKE_CASE=24_6534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1E-6 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , )-> str: lowerCamelCase_ =vocab_size lowerCamelCase_ =n_positions lowerCamelCase_ =n_embd lowerCamelCase_ =n_layer lowerCamelCase_ =n_head lowerCamelCase_ =dff lowerCamelCase_ =resid_pdrop lowerCamelCase_ =embd_pdrop lowerCamelCase_ =layer_norm_epsilon lowerCamelCase_ =initializer_range lowerCamelCase_ =use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __A : List[Any] = logging.get_logger(__name__) @add_end_docstrings( lowerCAmelCase__ , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> np.ndarray: if self.framework == "tf": lowerCamelCase_ =tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": lowerCamelCase_ =torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_SCREAMING_SNAKE_CASE ) else: raise ValueError("""Unsupported framework""" ) return masked_index def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> np.ndarray: lowerCamelCase_ =self.get_masked_index(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =np.prod(masked_index.shape ) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> Dict[str, GenericTensor]: if return_tensors is None: lowerCamelCase_ =self.framework lowerCamelCase_ =self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) self.ensure_exactly_one_mask_token(_SCREAMING_SNAKE_CASE ) return model_inputs def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =self.model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model_inputs["""input_ids"""] return model_outputs def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=None )-> Tuple: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: lowerCamelCase_ =target_ids.shape[0] lowerCamelCase_ =model_outputs["""input_ids"""][0] lowerCamelCase_ =model_outputs["""logits"""] if self.framework == "tf": lowerCamelCase_ =tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] lowerCamelCase_ =outputs.numpy() lowerCamelCase_ =outputs[0, masked_index, :] lowerCamelCase_ =stable_softmax(_SCREAMING_SNAKE_CASE , axis=-1 ) if target_ids is not None: lowerCamelCase_ =tf.gather_nd(tf.squeeze(_SCREAMING_SNAKE_CASE , 0 ) , target_ids.reshape(-1 , 1 ) ) lowerCamelCase_ =tf.expand_dims(_SCREAMING_SNAKE_CASE , 0 ) lowerCamelCase_ =tf.math.top_k(_SCREAMING_SNAKE_CASE , k=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ , lowerCamelCase_ =topk.values.numpy(), topk.indices.numpy() else: lowerCamelCase_ =torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_SCREAMING_SNAKE_CASE ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample lowerCamelCase_ =outputs[0, masked_index, :] lowerCamelCase_ =logits.softmax(dim=-1 ) if target_ids is not None: lowerCamelCase_ =probs[..., target_ids] lowerCamelCase_ , lowerCamelCase_ =probs.topk(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[] lowerCamelCase_ =values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): lowerCamelCase_ =[] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place lowerCamelCase_ =input_ids.numpy().copy() if target_ids is not None: lowerCamelCase_ =target_ids[p].tolist() lowerCamelCase_ =p # Filter padding out: lowerCamelCase_ =tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back lowerCamelCase_ =self.tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence} row.append(_SCREAMING_SNAKE_CASE ) result.append(_SCREAMING_SNAKE_CASE ) if single_mask: return result[0] return result def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> int: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[targets] try: lowerCamelCase_ =self.tokenizer.get_vocab() except Exception: lowerCamelCase_ ={} lowerCamelCase_ =[] for target in targets: lowerCamelCase_ =vocab.get(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if id_ is None: lowerCamelCase_ =self.tokenizer( _SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE , max_length=1 , truncation=_SCREAMING_SNAKE_CASE , )["""input_ids"""] if len(_SCREAMING_SNAKE_CASE ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' """We cannot replace it with anything meaningful, ignoring it""" ) continue lowerCamelCase_ =input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) lowerCamelCase_ =list(set(_SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""At least one target must be provided when passed.""" ) lowerCamelCase_ =np.array(_SCREAMING_SNAKE_CASE ) return target_ids def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> int: lowerCamelCase_ ={} if targets is not None: lowerCamelCase_ =self.get_target_ids(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =target_ids if top_k is not None: lowerCamelCase_ =top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""" ) return {}, {}, postprocess_params def __call__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) == 1: return outputs[0] return outputs
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> Union[str, Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext'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] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
713
from typing import Dict, Iterable, List, Optional, 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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) 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. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
from random import randint, random def __UpperCamelCase ( _A : int , _A : int , _A : int , _A : bool = False , _A : bool = False , _A : int = 5 , ) ->list: """simple docstring""" lowerCamelCase_ =[[-1] * number_of_cells] # Create a highway without any car lowerCamelCase_ =0 lowerCamelCase_ =max(_A , 0 ) while i < number_of_cells: lowerCamelCase_ =( randint(0 , _A ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def __UpperCamelCase ( _A : list , _A : int ) ->int: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =highway_now[car_index + 1 :] for cell in range(len(_A ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(_A , -1 ) def __UpperCamelCase ( _A : list , _A : float , _A : int ) ->list: """simple docstring""" lowerCamelCase_ =len(_A ) # Beforce calculations, the highway is empty lowerCamelCase_ =[-1] * number_of_cells for car_index in range(_A ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed lowerCamelCase_ =min(highway_now[car_index] + 1 , _A ) # Number of empty cell before the next car lowerCamelCase_ =get_distance(_A , _A ) - 1 # We can't have the car causing an accident lowerCamelCase_ =min(next_highway[car_index] , _A ) if random() < probability: # Randomly, a driver will slow down lowerCamelCase_ =max(next_highway[car_index] - 1 , 0 ) return next_highway def __UpperCamelCase ( _A : list , _A : int , _A : float , _A : int ) ->list: """simple docstring""" lowerCamelCase_ =len(highway[0] ) for i in range(_A ): lowerCamelCase_ =update(highway[i] , _A , _A ) lowerCamelCase_ =[-1] * number_of_cells for car_index in range(_A ): lowerCamelCase_ =next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) lowerCamelCase_ =(car_index + speed) % number_of_cells # Commit the change of position lowerCamelCase_ =speed highway.append(_A ) return highway if __name__ == "__main__": import doctest doctest.testmod()
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
0
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __A : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: super().__init__() self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 100 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , )-> Union[AudioPipelineOutput, Tuple]: if audio_length_in_s is None: lowerCamelCase_ =self.unet.config.sample_size / self.unet.config.sample_rate lowerCamelCase_ =audio_length_in_s * self.unet.config.sample_rate lowerCamelCase_ =2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f'{audio_length_in_s} is too small. Make sure it\'s bigger or equal to' f' {3 * down_scale_factor / self.unet.config.sample_rate}.' ) lowerCamelCase_ =int(_SCREAMING_SNAKE_CASE ) if sample_size % down_scale_factor != 0: lowerCamelCase_ =( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f'{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled' f' by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising' """ process.""" ) lowerCamelCase_ =int(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =next(iter(self.unet.parameters() ) ).dtype lowerCamelCase_ =(batch_size, self.unet.config.in_channels, sample_size) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) lowerCamelCase_ =randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=self.device , dtype=_SCREAMING_SNAKE_CASE ) # set step values self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=audio.device ) lowerCamelCase_ =self.scheduler.timesteps.to(_SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowerCamelCase_ =self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. compute previous image: x_t -> t_t-1 lowerCamelCase_ =self.scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).prev_sample lowerCamelCase_ =audio.clamp(-1 , 1 ).float().cpu().numpy() lowerCamelCase_ =audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=_SCREAMING_SNAKE_CASE )
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A : int = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Dict = ["input_features", "attention_mask"] def __init__( self , _SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=1_6000 , _SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(feature_size=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , padding_value=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =num_mel_bins lowerCamelCase_ =do_ceptral_normalize lowerCamelCase_ =normalize_means lowerCamelCase_ =normalize_vars lowerCamelCase_ =True def _snake_case ( self , _SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =waveform * (2**15) # Kaldi compliance: 16-bit signed integers lowerCamelCase_ =torch.from_numpy(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) lowerCamelCase_ =ta_kaldi.fbank(_SCREAMING_SNAKE_CASE , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 0.0 , )-> np.ndarray: # make sure we normalize float32 arrays if normalize_means: lowerCamelCase_ =x[:input_length].mean(axis=0 ) lowerCamelCase_ =np.subtract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if normalize_vars: lowerCamelCase_ =x[:input_length].std(axis=0 ) lowerCamelCase_ =np.divide(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if input_length < x.shape[0]: lowerCamelCase_ =padding_value # make sure array is in float32 lowerCamelCase_ =x.astype(np.floataa ) return x def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[np.ndarray]: lowerCamelCase_ =attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) lowerCamelCase_ =isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) lowerCamelCase_ =is_batched_numpy or ( isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase_ =[np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): lowerCamelCase_ =np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCamelCase_ =raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase_ =[raw_speech] # extract fbank features lowerCamelCase_ =[self._extract_fbank_features(_SCREAMING_SNAKE_CASE ) for waveform in raw_speech] # convert into correct format for padding lowerCamelCase_ =BatchFeature({"""input_features""": features} ) lowerCamelCase_ =self.pad( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # make sure list is in array format lowerCamelCase_ =padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in input_features] lowerCamelCase_ =padded_inputs.get("""attention_mask""" ) if attention_mask is not None: lowerCamelCase_ =[np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: lowerCamelCase_ =( np.array(_SCREAMING_SNAKE_CASE , dtype=np.intaa ) if self._get_padding_strategies(_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) is not PaddingStrategy.DO_NOT_PAD else None ) lowerCamelCase_ =self.normalize( padded_inputs["""input_features"""] , attention_mask=_SCREAMING_SNAKE_CASE ) if return_tensors is not None: lowerCamelCase_ =padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE ) return padded_inputs
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import functools from typing import Any def __UpperCamelCase ( _A : str , _A : list[str] ) ->bool: """simple docstring""" # Validation if not isinstance(_A , _A ) or len(_A ) == 0: raise ValueError("""the string should be not empty string""" ) if not isinstance(_A , _A ) or not all( isinstance(_A , _A ) and len(_A ) > 0 for item in words ): raise ValueError("""the words should be a list of non-empty strings""" ) # Build trie lowerCamelCase_ ={} lowerCamelCase_ ="""WORD_KEEPER""" for word in words: lowerCamelCase_ =trie for c in word: if c not in trie_node: lowerCamelCase_ ={} lowerCamelCase_ =trie_node[c] lowerCamelCase_ =True lowerCamelCase_ =len(_A ) # Dynamic programming method @functools.cache def is_breakable(_A : int ) -> bool: if index == len_string: return True lowerCamelCase_ =trie for i in range(_A , _A ): lowerCamelCase_ =trie_node.get(string[i] , _A ) if trie_node is None: return False if trie_node.get(_A , _A ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
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_barthez import BarthezTokenizer else: __A : Union[str, Any] = None __A : str = logging.get_logger(__name__) __A : List[str] = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} __A : Dict = { 'vocab_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json' ), }, } __A : Optional[int] = { 'moussaKam/mbarthez': 10_24, 'moussaKam/barthez': 10_24, 'moussaKam/barthez-orangesum-title': 10_24, } __A : Optional[int] = '▁' class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:int = VOCAB_FILES_NAMES _UpperCamelCase:Dict = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase:Union[str, Any] = ["input_ids", "attention_mask"] _UpperCamelCase:Tuple = BarthezTokenizer def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , **_SCREAMING_SNAKE_CASE , )-> Optional[Any]: # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token super().__init__( _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =vocab_file lowerCamelCase_ =False if not self.vocab_file else True def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] lowerCamelCase_ =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' from typing import Dict, Iterable, List, Optional, 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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) 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. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __A : Any = logging.get_logger(__name__) def __UpperCamelCase ( _A : Tuple , _A : Any ) ->List[Any]: """simple docstring""" lowerCamelCase_ =set() lowerCamelCase_ =[] def parse_line(_A : List[Any] ): for line in fp: if isinstance(_A , _A ): lowerCamelCase_ =line.decode("""UTF-8""" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(""" """ ): # process a single warning and move it to `selected_warnings`. if len(_A ) > 0: lowerCamelCase_ ="""\n""".join(_A ) # Only keep the warnings specified in `targets` if any(f': {x}: ' in warning for x in targets ): selected_warnings.add(_A ) buffer.clear() continue else: lowerCamelCase_ =line.strip() buffer.append(_A ) if from_gh: for filename in os.listdir(_A ): lowerCamelCase_ =os.path.join(_A , _A ) if not os.path.isdir(_A ): # read the file if filename != "warnings.txt": continue with open(_A ) as fp: parse_line(_A ) else: try: with zipfile.ZipFile(_A ) as z: for filename in z.namelist(): if not os.path.isdir(_A ): # read the file if filename != "warnings.txt": continue with z.open(_A ) as fp: parse_line(_A ) except Exception: logger.warning( f'{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.' ) return selected_warnings def __UpperCamelCase ( _A : Optional[Any] , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =set() lowerCamelCase_ =[os.path.join(_A , _A ) for p in os.listdir(_A ) if (p.endswith(""".zip""" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(_A , _A ) ) return selected_warnings if __name__ == "__main__": def __UpperCamelCase ( _A : Dict ) ->Optional[int]: """simple docstring""" return values.split(""",""" ) __A : int = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') # optional parameters parser.add_argument( '--targets', default='DeprecationWarning,UserWarning,FutureWarning', type=list_str, help='Comma-separated list of target warning(s) which we want to extract.', ) parser.add_argument( '--from_gh', action='store_true', help='If running from a GitHub action workflow and collecting warnings from its artifacts.', ) __A : Union[str, Any] = parser.parse_args() __A : Union[str, Any] = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __A : Optional[int] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('=' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __A : Optional[int] = extract_warnings(args.output_dir, args.targets) __A : Tuple = sorted(selected_warnings) with open(os.path.join(args.output_dir, 'selected_warnings.json'), 'w', encoding='UTF-8') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[str] = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """swinv2""" a__ = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self : int , UpperCamelCase__ : Tuple=224 , UpperCamelCase__ : Any=4 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Optional[Any]=96 , UpperCamelCase__ : str=[2, 2, 6, 2] , UpperCamelCase__ : Union[str, Any]=[3, 6, 12, 24] , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : int=4.0 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Any=0.0 , UpperCamelCase__ : Union[str, Any]=0.0 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : Dict=1E-5 , UpperCamelCase__ : List[str]=32 , **UpperCamelCase__ : int , ) -> Union[str, Any]: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = image_size __magic_name__ = patch_size __magic_name__ = num_channels __magic_name__ = embed_dim __magic_name__ = depths __magic_name__ = len(UpperCamelCase__ ) __magic_name__ = num_heads __magic_name__ = window_size __magic_name__ = mlp_ratio __magic_name__ = qkv_bias __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = drop_path_rate __magic_name__ = hidden_act __magic_name__ = use_absolute_embeddings __magic_name__ = layer_norm_eps __magic_name__ = initializer_range __magic_name__ = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __magic_name__ = int(embed_dim * 2 ** (len(UpperCamelCase__ ) - 1) ) __magic_name__ = (0, 0, 0, 0)
76
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Any ) -> Any: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Tuple ) -> Any: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , ) def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple: """simple docstring""" __magic_name__ = NystromformerModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str: """simple docstring""" __magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a__ = False a__ = False def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = NystromformerModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : str ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def _lowercase ( self : str ) -> Tuple: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) ) @slow def _lowercase ( self : int ) -> str: """simple docstring""" __magic_name__ = """the [MASK] of Belgium is Brussels""" __magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" ) with torch.no_grad(): __magic_name__ = model(encoding.input_ids ).logits __magic_name__ = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
76
1
__lowerCAmelCase : Union[str, Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' __lowerCAmelCase : Dict = [{'type': 'code', 'content': INSTALL_CONTENT}] __lowerCAmelCase : Optional[Any] = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Union[str, Any] = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """cvt""" def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = num_channels __magic_name__ = patch_sizes __magic_name__ = patch_stride __magic_name__ = patch_padding __magic_name__ = embed_dim __magic_name__ = num_heads __magic_name__ = depth __magic_name__ = mlp_ratio __magic_name__ = attention_drop_rate __magic_name__ = drop_rate __magic_name__ = drop_path_rate __magic_name__ = qkv_bias __magic_name__ = cls_token __magic_name__ = qkv_projection_method __magic_name__ = kernel_qkv __magic_name__ = padding_kv __magic_name__ = stride_kv __magic_name__ = padding_q __magic_name__ = stride_q __magic_name__ = initializer_range __magic_name__ = layer_norm_eps
76
1
import gc import threading import time import psutil import torch class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ) -> Dict: """simple docstring""" __magic_name__ = psutil.Process() __magic_name__ = False def _lowercase ( self : int ) -> Tuple: """simple docstring""" __magic_name__ = -1 while True: __magic_name__ = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def _lowercase ( self : List[Any] ) -> Tuple: """simple docstring""" __magic_name__ = True __magic_name__ = threading.Thread(target=self.peak_monitor ) __magic_name__ = True self.thread.start() def _lowercase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __magic_name__ = False self.thread.join() return self.cpu_memory_peak __lowerCAmelCase : int = PeakCPUMemory() def a__ ( ): '''simple docstring''' __magic_name__ = {"""time""": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem __magic_name__ = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): __magic_name__ = torch.cuda.memory_allocated(A_ ) torch.cuda.reset_peak_memory_stats() return measures def a__ ( A_ ): '''simple docstring''' __magic_name__ = {"""time""": time.time() - start_measures["""time"""]} gc.collect() torch.cuda.empty_cache() # CPU mem __magic_name__ = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20 __magic_name__ = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): __magic_name__ = (torch.cuda.memory_allocated(A_ ) - start_measures[str(A_ )]) / 2**20 __magic_name__ = (torch.cuda.max_memory_allocated(A_ ) - start_measures[str(A_ )]) / 2**20 return measures def a__ ( A_, A_ ): '''simple docstring''' print(f'''{description}:''' ) print(f'''- Time: {measures['time']:.2f}s''' ) for i in range(torch.cuda.device_count() ): print(f'''- GPU {i} allocated: {measures[str(A_ )]:.2f}MiB''' ) __magic_name__ = measures[f'''{i}-peak'''] print(f'''- GPU {i} peak: {peak:.2f}MiB''' ) print(f'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''' ) print(f'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''' )
76
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase : List[str] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[Any] = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys __lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
1
__lowerCAmelCase : Any = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
76
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""projector.weight"""] __magic_name__ = downstream_dict["""projector.bias"""] __magic_name__ = downstream_dict["""model.post_net.linear.weight"""] __magic_name__ = downstream_dict["""model.post_net.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""model.linear.weight"""] __magic_name__ = downstream_dict["""model.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""connector.weight"""] __magic_name__ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __magic_name__ = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] __magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] __magic_name__ = downstream_dict["""objective.W"""] return model @torch.no_grad() def a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = torch.load(A_, map_location="""cpu""" ) __magic_name__ = checkpoint["""Downstream"""] __magic_name__ = WavaVecaConfig.from_pretrained(A_ ) __magic_name__ = WavaVecaFeatureExtractor.from_pretrained( A_, return_attention_mask=A_, do_normalize=A_ ) __magic_name__ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): __magic_name__ = convert_classification(A_, A_, A_ ) elif arch.endswith("""ForAudioFrameClassification""" ): __magic_name__ = convert_diarization(A_, A_, A_ ) elif arch.endswith("""ForXVector""" ): __magic_name__ = convert_xvector(A_, A_, A_ ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: __magic_name__ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(A_ ) hf_model.save_pretrained(A_ ) if __name__ == "__main__": __lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __lowerCAmelCase : str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
76
1
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, 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, logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 256} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" __magic_name__ = get_size_dict(UpperCamelCase__ ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = 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. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a__ ( A_, A_ ): '''simple docstring''' assert isinstance(A_, A_ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read() _check_text_dataset(A_, A_ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""", [str, list] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if issubclass(A_, A_ ): __magic_name__ = text_path elif issubclass(A_, A_ ): __magic_name__ = [text_path] __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) def a__ ( A_, A_, A_=("train",) ): '''simple docstring''' assert isinstance(A_, A_ ) for split in splits: __magic_name__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if split: __magic_name__ = {split: text_path} else: __magic_name__ = """train""" __magic_name__ = {"""train""": text_path, """test""": text_path} __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
76
1
from __future__ import annotations def a__ ( A_ ): '''simple docstring''' if len(A_ ) < 2: raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" ) if any(i <= 0 for i in nums ): raise ValueError("""All values must be greater than 0""" ) __magic_name__ = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
76
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, 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, logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 256} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" __magic_name__ = get_size_dict(UpperCamelCase__ ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = 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. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
1
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self : List[Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = """hf-internal-testing/tiny-random-t5""" __magic_name__ = AutoTokenizer.from_pretrained(UpperCamelCase__ ) __magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ) __magic_name__ = tokenizer("""This is me""" , return_tensors="""pt""" ) __magic_name__ = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __magic_name__ = model.generate(**UpperCamelCase__ ) __magic_name__ = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) __magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __magic_name__ = model_reloaded.generate(**UpperCamelCase__ ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) def _lowercase ( self : int ) -> int: """simple docstring""" __magic_name__ = """hf-internal-testing/tiny-random-t5""" __magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ) __magic_name__ = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(UpperCamelCase__ ): model.save_pretrained(UpperCamelCase__ ) __magic_name__ = model.reverse_bettertransformer() model.save_pretrained(UpperCamelCase__ )
76
import math def a__ ( A_, A_ = 0, A_ = 0 ): '''simple docstring''' __magic_name__ = end or len(A_ ) for i in range(A_, A_ ): __magic_name__ = i __magic_name__ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __magic_name__ = array[temp_index - 1] temp_index -= 1 __magic_name__ = temp_index_value return array def a__ ( A_, A_, A_ ): # Max Heap '''simple docstring''' __magic_name__ = index __magic_name__ = 2 * index + 1 # Left Node __magic_name__ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __magic_name__ = left_index if right_index < heap_size and array[largest] < array[right_index]: __magic_name__ = right_index if largest != index: __magic_name__ , __magic_name__ = array[largest], array[index] heapify(A_, A_, A_ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = len(A_ ) for i in range(n // 2, -1, -1 ): heapify(A_, A_, A_ ) for i in range(n - 1, 0, -1 ): __magic_name__ , __magic_name__ = array[0], array[i] heapify(A_, 0, A_ ) return array def a__ ( A_, A_, A_, A_ ): '''simple docstring''' 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 a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = low __magic_name__ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __magic_name__ , __magic_name__ = array[j], array[i] i += 1 def a__ ( A_ ): '''simple docstring''' if len(A_ ) == 0: return array __magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) ) __magic_name__ = 16 return intro_sort(A_, 0, len(A_ ), A_, A_ ) def a__ ( A_, A_, A_, A_, A_ ): '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(A_ ) max_depth -= 1 __magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 ) __magic_name__ = partition(A_, A_, A_, A_ ) intro_sort(A_, A_, A_, A_, A_ ) __magic_name__ = p return insertion_sort(A_, A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip() __lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')] print(sort(unsorted))
76
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCAmelCase : List[str] = { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """speech_to_text_2""" a__ = ["""past_key_values"""] a__ = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[Any] , UpperCamelCase__ : Optional[int]=1_0000 , UpperCamelCase__ : str=6 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : List[str]=4 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : str=True , UpperCamelCase__ : Optional[int]="relu" , UpperCamelCase__ : str=256 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : List[Any]=0.0 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Union[str, Any]=True , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : str=0 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : Optional[Any]=1024 , **UpperCamelCase__ : str , ) -> int: """simple docstring""" __magic_name__ = vocab_size __magic_name__ = d_model __magic_name__ = decoder_ffn_dim __magic_name__ = decoder_layers __magic_name__ = decoder_attention_heads __magic_name__ = dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = activation_function __magic_name__ = init_std __magic_name__ = decoder_layerdrop __magic_name__ = use_cache __magic_name__ = decoder_layers __magic_name__ = scale_embedding # scale factor will be sqrt(d_model) if True __magic_name__ = max_target_positions super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
76
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) __magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ ) if matches: __magic_name__ = float(matches[1] ) __magic_name__ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __magic_name__ = 1001 __magic_name__ = """imagenet-1k-id2label.json""" __magic_name__ = """huggingface/label-files""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()} __magic_name__ = """background""" __magic_name__ = idalabel __magic_name__ = {v: k for k, v in idalabel.items()} return config def a__ ( ): '''simple docstring''' __magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" __magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ) return im @torch.no_grad() def a__ ( A_, A_, A_, A_=False ): '''simple docstring''' __magic_name__ = get_mobilenet_va_config(A_ ) # Load 🤗 model __magic_name__ = MobileNetVaForImageClassification(A_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(A_, A_, A_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __magic_name__ = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, ) __magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" ) __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __magic_name__ = None if expected_logits is not None: assert torch.allclose(logits[0, :3], A_, atol=1e-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if push_to_hub: print("""Pushing to the hub...""" ) __magic_name__ = """google/""" + model_name image_processor.push_to_hub(A_ ) model.push_to_hub(A_ ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : str = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
76
1
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowerCAmelCase : Optional[int] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowerCAmelCase : Union[str, Any] = [0, 25, 50] __lowerCAmelCase : Optional[int] = [25, 50, 75] __lowerCAmelCase : str = fuzz.membership.trimf(X, abca) __lowerCAmelCase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowerCAmelCase : Optional[int] = np.ones(75) __lowerCAmelCase : List[str] = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowerCAmelCase : Optional[int] = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowerCAmelCase : str = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowerCAmelCase : Optional[Any] = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowerCAmelCase : List[str] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowerCAmelCase : Tuple = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowerCAmelCase : List[Any] = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowerCAmelCase : Tuple = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowerCAmelCase : Optional[Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
76
import collections import importlib.util import os import re from pathlib import Path __lowerCAmelCase : int = 'src/transformers' # Matches is_xxx_available() __lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} __lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", __lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], __lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo __lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: __lowerCAmelCase : int = re.compile(R'^\s*try:') # Catches a line with else: __lowerCAmelCase : Tuple = re.compile(R'^\s*else:') def a__ ( A_ ): '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None __magic_name__ = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def a__ ( A_ ): '''simple docstring''' with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f: __magic_name__ = f.readlines() __magic_name__ = 0 while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure __magic_name__ = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: __magic_name__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): __magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0] __magic_name__ = re.findall("""\[([^\]]+)\]""", A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue __magic_name__ = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: __magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): __magic_name__ = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: __magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: __magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 __magic_name__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __magic_name__ = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 __magic_name__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def a__ ( A_, A_ ): '''simple docstring''' def find_duplicates(A_ ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __magic_name__ = [] for key in import_dict_objects.keys(): __magic_name__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) __magic_name__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __magic_name__ = """base imports""" if key == """none""" else f'''{key} backend''' errors.append(f'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def a__ ( ): '''simple docstring''' __magic_name__ = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: __magic_name__ = os.path.join(A_, """__init__.py""" ) __magic_name__ = parse_init(A_ ) if objects is not None: __magic_name__ = analyze_results(*A_ ) if len(A_ ) > 0: __magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("""\n""".join(A_ ) ) if len(A_ ) > 0: raise ValueError("""\n\n""".join(A_ ) ) def a__ ( ): '''simple docstring''' __magic_name__ = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0: continue __magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) ) __magic_name__ = short_path.replace(os.path.sep, """.""" ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue __magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) ) __magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(A_ ) return submodules __lowerCAmelCase : Dict = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def a__ ( ): '''simple docstring''' __magic_name__ = importlib.util.spec_from_file_location( """transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) __magic_name__ = spec.loader.load_module() __magic_name__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: __magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registered in the main init of Transformers:\n""" f'''{list_of_modules}\n''' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
76
1
from __future__ import annotations from typing import Any class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] , UpperCamelCase__ : int = 6 ) -> None: """simple docstring""" __magic_name__ = None __magic_name__ = None self.create_linked_list(UpperCamelCase__ ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : int ) -> None: """simple docstring""" __magic_name__ = Node() __magic_name__ = current_node __magic_name__ = current_node __magic_name__ = current_node for _ in range(1 , UpperCamelCase__ ): __magic_name__ = Node() __magic_name__ = current_node __magic_name__ = previous_node __magic_name__ = current_node __magic_name__ = self.front __magic_name__ = previous_node def _lowercase ( self : Optional[int] ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _lowercase ( self : Optional[int] ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def _lowercase ( self : List[Any] , UpperCamelCase__ : Any ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): __magic_name__ = self.rear.next if self.rear: __magic_name__ = data def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: __magic_name__ = self.front.data __magic_name__ = None return data __magic_name__ = self.front __magic_name__ = old_front.next __magic_name__ = old_front.data __magic_name__ = None return data def _lowercase ( self : Optional[Any] ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def _lowercase ( self : str ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class UpperCAmelCase_ : '''simple docstring''' def __init__( self : int ) -> None: """simple docstring""" __magic_name__ = None __magic_name__ = None __magic_name__ = None if __name__ == "__main__": import doctest doctest.testmod()
76
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[Any] = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """sew-d""" def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) __magic_name__ = hidden_size __magic_name__ = feat_extract_norm __magic_name__ = feat_extract_activation __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = conv_bias __magic_name__ = num_conv_pos_embeddings __magic_name__ = num_conv_pos_embedding_groups __magic_name__ = len(self.conv_dim ) __magic_name__ = num_hidden_layers __magic_name__ = intermediate_size __magic_name__ = squeeze_factor __magic_name__ = max_position_embeddings __magic_name__ = position_buckets __magic_name__ = share_att_key __magic_name__ = relative_attention __magic_name__ = norm_rel_ebd __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = hidden_act __magic_name__ = num_attention_heads __magic_name__ = hidden_dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = feat_proj_dropout __magic_name__ = final_dropout __magic_name__ = layer_norm_eps __magic_name__ = feature_layer_norm_eps __magic_name__ = initializer_range __magic_name__ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __magic_name__ = apply_spec_augment __magic_name__ = mask_time_prob __magic_name__ = mask_time_length __magic_name__ = mask_time_min_masks __magic_name__ = mask_feature_prob __magic_name__ = mask_feature_length __magic_name__ = mask_feature_min_masks # ctc loss __magic_name__ = ctc_loss_reduction __magic_name__ = ctc_zero_infinity # sequence classification __magic_name__ = use_weighted_layer_sum __magic_name__ = classifier_proj_size @property def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
76
1
from math import pi, sqrt, tan def a__ ( A_ ): '''simple docstring''' if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length**2 def a__ ( A_, A_, A_ ): '''simple docstring''' if length < 0 or breadth < 0 or height < 0: raise ValueError("""surface_area_cuboid() only accepts non-negative values""" ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def a__ ( A_ ): '''simple docstring''' if radius < 0: raise ValueError("""surface_area_sphere() only accepts non-negative values""" ) return 4 * pi * radius**2 def a__ ( A_ ): '''simple docstring''' if radius < 0: raise ValueError("""surface_area_hemisphere() only accepts non-negative values""" ) return 3 * pi * radius**2 def a__ ( A_, A_ ): '''simple docstring''' if radius < 0 or height < 0: raise ValueError("""surface_area_cone() only accepts non-negative values""" ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def a__ ( A_, A_, A_ ): '''simple docstring''' if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( """surface_area_conical_frustum() only accepts non-negative values""" ) __magic_name__ = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def a__ ( A_, A_ ): '''simple docstring''' if radius < 0 or height < 0: raise ValueError("""surface_area_cylinder() only accepts non-negative values""" ) return 2 * pi * radius * (height + radius) def a__ ( A_, A_ ): '''simple docstring''' if torus_radius < 0 or tube_radius < 0: raise ValueError("""surface_area_torus() only accepts non-negative values""" ) if torus_radius < tube_radius: raise ValueError( """surface_area_torus() does not support spindle or self intersecting tori""" ) return 4 * pow(A_, 2 ) * torus_radius * tube_radius def a__ ( A_, A_ ): '''simple docstring''' if length < 0 or width < 0: raise ValueError("""area_rectangle() only accepts non-negative values""" ) return length * width def a__ ( A_ ): '''simple docstring''' if side_length < 0: raise ValueError("""area_square() only accepts non-negative values""" ) return side_length**2 def a__ ( A_, A_ ): '''simple docstring''' if base < 0 or height < 0: raise ValueError("""area_triangle() only accepts non-negative values""" ) return (base * height) / 2 def a__ ( A_, A_, A_ ): '''simple docstring''' if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError("""area_triangle_three_sides() only accepts non-negative values""" ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError("""Given three sides do not form a triangle""" ) __magic_name__ = (sidea + sidea + sidea) / 2 __magic_name__ = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def a__ ( A_, A_ ): '''simple docstring''' if base < 0 or height < 0: raise ValueError("""area_parallelogram() only accepts non-negative values""" ) return base * height def a__ ( A_, A_, A_ ): '''simple docstring''' if basea < 0 or basea < 0 or height < 0: raise ValueError("""area_trapezium() only accepts non-negative values""" ) return 1 / 2 * (basea + basea) * height def a__ ( A_ ): '''simple docstring''' if radius < 0: raise ValueError("""area_circle() only accepts non-negative values""" ) return pi * radius**2 def a__ ( A_, A_ ): '''simple docstring''' if radius_x < 0 or radius_y < 0: raise ValueError("""area_ellipse() only accepts non-negative values""" ) return pi * radius_x * radius_y def a__ ( A_, A_ ): '''simple docstring''' if diagonal_a < 0 or diagonal_a < 0: raise ValueError("""area_rhombus() only accepts non-negative values""" ) return 1 / 2 * diagonal_a * diagonal_a def a__ ( A_, A_ ): '''simple docstring''' if not isinstance(A_, A_ ) or sides < 3: raise ValueError( """area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides""" ) elif length < 0: raise ValueError( """area_reg_polygon() only accepts non-negative values as \ length of a side""" ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('[DEMO] Areas of various geometric shapes: \n') print(F'''Rectangle: {area_rectangle(10, 20) = }''') print(F'''Square: {area_square(10) = }''') print(F'''Triangle: {area_triangle(10, 10) = }''') print(F'''Triangle: {area_triangle_three_sides(5, 12, 13) = }''') print(F'''Parallelogram: {area_parallelogram(10, 20) = }''') print(F'''Rhombus: {area_rhombus(10, 20) = }''') print(F'''Trapezium: {area_trapezium(10, 20, 30) = }''') print(F'''Circle: {area_circle(20) = }''') print(F'''Ellipse: {area_ellipse(10, 20) = }''') print('\nSurface Areas of various geometric shapes: \n') print(F'''Cube: {surface_area_cube(20) = }''') print(F'''Cuboid: {surface_area_cuboid(10, 20, 30) = }''') print(F'''Sphere: {surface_area_sphere(20) = }''') print(F'''Hemisphere: {surface_area_hemisphere(20) = }''') print(F'''Cone: {surface_area_cone(10, 20) = }''') print(F'''Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }''') print(F'''Cylinder: {surface_area_cylinder(10, 20) = }''') print(F'''Torus: {surface_area_torus(20, 10) = }''') print(F'''Equilateral Triangle: {area_reg_polygon(3, 10) = }''') print(F'''Square: {area_reg_polygon(4, 10) = }''') print(F'''Reqular Pentagon: {area_reg_polygon(5, 10) = }''')
76
import math import random def a__ ( A_, A_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __lowerCAmelCase : Union[str, Any] = 0.02 def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = float(2 * (random.randint(1, 100 )) - 1 ) for _ in range(A_ ): # Forward propagation __magic_name__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __magic_name__ = (expected / 100) - layer_a # Error delta __magic_name__ = layer_1_error * sigmoid_function(A_, A_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : List[Any] = int(input('Expected value: ')) __lowerCAmelCase : Tuple = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
76
1
class UpperCAmelCase_ : '''simple docstring''' def __init__( self : str , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ) -> int: """simple docstring""" __magic_name__ = name __magic_name__ = val def __str__( self : str ) -> Union[str, Any]: """simple docstring""" return F'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self : List[str] , UpperCamelCase__ : Any ) -> int: """simple docstring""" return self.val < other.val class UpperCAmelCase_ : '''simple docstring''' def __init__( self : List[str] , UpperCamelCase__ : Any ) -> Any: """simple docstring""" __magic_name__ = {} __magic_name__ = {} __magic_name__ = self.build_heap(UpperCamelCase__ ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Optional[int] ) -> Optional[int]: """simple docstring""" return self.get_value(UpperCamelCase__ ) def _lowercase ( self : str , UpperCamelCase__ : Optional[int] ) -> Optional[Any]: """simple docstring""" return (idx - 1) // 2 def _lowercase ( self : Dict , UpperCamelCase__ : Tuple ) -> Any: """simple docstring""" return idx * 2 + 1 def _lowercase ( self : Dict , UpperCamelCase__ : Any ) -> str: """simple docstring""" return idx * 2 + 2 def _lowercase ( self : Any , UpperCamelCase__ : List[Any] ) -> Union[str, Any]: """simple docstring""" return self.heap_dict[key] def _lowercase ( self : List[str] , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" __magic_name__ = len(UpperCamelCase__ ) - 1 __magic_name__ = self.get_parent_idx(UpperCamelCase__ ) for idx, i in enumerate(UpperCamelCase__ ): __magic_name__ = idx __magic_name__ = i.val for i in range(UpperCamelCase__ , -1 , -1 ): self.sift_down(UpperCamelCase__ , UpperCamelCase__ ) return array def _lowercase ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] ) -> Optional[int]: """simple docstring""" while True: __magic_name__ = self.get_left_child_idx(UpperCamelCase__ ) # noqa: E741 __magic_name__ = self.get_right_child_idx(UpperCamelCase__ ) __magic_name__ = idx if l < len(UpperCamelCase__ ) and array[l] < array[idx]: __magic_name__ = l if r < len(UpperCamelCase__ ) and array[r] < array[smallest]: __magic_name__ = r if smallest != idx: __magic_name__ , __magic_name__ = array[smallest], array[idx] ( ( __magic_name__ ) , ( __magic_name__ ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) __magic_name__ = smallest else: break def _lowercase ( self : str , UpperCamelCase__ : str ) -> str: """simple docstring""" __magic_name__ = self.get_parent_idx(UpperCamelCase__ ) while p >= 0 and self.heap[p] > self.heap[idx]: __magic_name__ , __magic_name__ = self.heap[idx], self.heap[p] __magic_name__ , __magic_name__ = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) __magic_name__ = p __magic_name__ = self.get_parent_idx(UpperCamelCase__ ) def _lowercase ( self : int ) -> Tuple: """simple docstring""" return self.heap[0] def _lowercase ( self : Tuple ) -> List[str]: """simple docstring""" __magic_name__ , __magic_name__ = self.heap[-1], self.heap[0] __magic_name__ , __magic_name__ = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) __magic_name__ = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def _lowercase ( self : List[str] , UpperCamelCase__ : int ) -> Union[str, Any]: """simple docstring""" self.heap.append(UpperCamelCase__ ) __magic_name__ = len(self.heap ) - 1 __magic_name__ = node.val self.sift_up(len(self.heap ) - 1 ) def _lowercase ( self : Optional[Any] ) -> str: """simple docstring""" return len(self.heap ) == 0 def _lowercase ( self : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple ) -> List[str]: """simple docstring""" assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" __magic_name__ = new_value __magic_name__ = new_value self.sift_up(self.idx_of_element[node] ) __lowerCAmelCase : Union[str, Any] = Node('R', -1) __lowerCAmelCase : Tuple = Node('B', 6) __lowerCAmelCase : int = Node('A', 3) __lowerCAmelCase : Union[str, Any] = Node('X', 1) __lowerCAmelCase : List[Any] = Node('E', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __lowerCAmelCase : Tuple = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('Min Heap - before decrease key') for i in my_min_heap.heap: print(i) print('Min Heap - After decrease key of node [B -> -17]') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
76
import os import sys __lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowerCAmelCase : Union[str, Any] = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoConfig.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoTokenizer.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModel.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModel.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
76
1
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowerCAmelCase : int = 16 __lowerCAmelCase : List[str] = 32 def a__ ( A_, A_ = 16, A_ = "bert-base-cased" ): '''simple docstring''' __magic_name__ = AutoTokenizer.from_pretrained(A_ ) __magic_name__ = load_dataset("""glue""", """mrpc""" ) def tokenize_function(A_ ): # max_length=None => use the model max length (it's actually the default) __magic_name__ = tokenizer(examples["""sentence1"""], examples["""sentence2"""], truncation=A_, max_length=A_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __magic_name__ = datasets.map( A_, batched=A_, remove_columns=["""idx""", """sentence1""", """sentence2"""], load_from_cache_file=A_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __magic_name__ = tokenized_datasets.rename_column("""label""", """labels""" ) def collate_fn(A_ ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A_, padding="""max_length""", max_length=128, return_tensors="""pt""" ) return tokenizer.pad(A_, padding="""longest""", return_tensors="""pt""" ) # Instantiate dataloaders. __magic_name__ = DataLoader( tokenized_datasets["""train"""], shuffle=A_, collate_fn=A_, batch_size=A_ ) __magic_name__ = DataLoader( tokenized_datasets["""validation"""], shuffle=A_, collate_fn=A_, batch_size=A_ ) return train_dataloader, eval_dataloader def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __magic_name__ = config["""lr"""] __magic_name__ = int(config["""num_epochs"""] ) __magic_name__ = int(config["""seed"""] ) __magic_name__ = int(config["""batch_size"""] ) __magic_name__ = args.model_name_or_path set_seed(A_ ) __magic_name__ , __magic_name__ = get_dataloaders(A_, A_, A_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __magic_name__ = AutoModelForSequenceClassification.from_pretrained(A_, return_dict=A_ ) # Instantiate optimizer __magic_name__ = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __magic_name__ = optimizer_cls(params=model.parameters(), lr=A_ ) if accelerator.state.deepspeed_plugin is not None: __magic_name__ = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: __magic_name__ = 1 __magic_name__ = (len(A_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __magic_name__ = get_linear_schedule_with_warmup( optimizer=A_, num_warmup_steps=0, num_training_steps=A_, ) else: __magic_name__ = DummyScheduler(A_, total_num_steps=A_, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = accelerator.prepare( A_, A_, A_, A_, A_ ) # We need to keep track of how many total steps we have iterated over __magic_name__ = 0 # We also need to keep track of the stating epoch so files are named properly __magic_name__ = 0 # Now we train the model __magic_name__ = evaluate.load("""glue""", """mrpc""" ) __magic_name__ = 0 __magic_name__ = {} for epoch in range(A_, A_ ): model.train() for step, batch in enumerate(A_ ): __magic_name__ = model(**A_ ) __magic_name__ = outputs.loss __magic_name__ = loss / gradient_accumulation_steps accelerator.backward(A_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() __magic_name__ = 0 for step, batch in enumerate(A_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __magic_name__ , __magic_name__ = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(A_ ) - 1: __magic_name__ = predictions[: len(eval_dataloader.dataset ) - samples_seen] __magic_name__ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=A_, references=A_, ) __magic_name__ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''', A_ ) __magic_name__ = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: __magic_name__ = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, """all_results.json""" ), """w""" ) as f: json.dump(A_, A_ ) def a__ ( ): '''simple docstring''' __magic_name__ = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""", type=A_, default="""bert-base-cased""", help="""Path to pretrained model or model identifier from huggingface.co/models.""", required=A_, ) parser.add_argument( """--output_dir""", type=A_, default=""".""", help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""", ) parser.add_argument( """--performance_lower_bound""", type=A_, default=A_, help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""", ) parser.add_argument( """--num_epochs""", type=A_, default=3, help="""Number of train epochs.""", ) __magic_name__ = parser.parse_args() __magic_name__ = {"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(A_, A_ ) if __name__ == "__main__": main()
76
from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str: """simple docstring""" if tokenize_kwargs is None: __magic_name__ = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) __magic_name__ = truncation __magic_name__ = tokenize_kwargs __magic_name__ = {} if return_tensors is not None: __magic_name__ = return_tensors return preprocess_params, {}, postprocess_params def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]: """simple docstring""" __magic_name__ = self.framework __magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) return model_inputs def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str: """simple docstring""" __magic_name__ = self.model(**UpperCamelCase__ ) return model_outputs def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]: """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
76
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy __lowerCAmelCase : Any = logging.getLogger(__name__) __lowerCAmelCase : List[Any] = 'pytorch_model.bin' @dataclasses.dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = dataclasses.field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models."""} ) a__ = dataclasses.field( default=_A , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co."""} , ) @dataclasses.dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = dataclasses.field(metadata={"""help""": """A csv or a json file containing the training data."""} ) a__ = dataclasses.field(metadata={"""help""": """A csv or a json file containing the data to predict on."""} ) a__ = dataclasses.field( default=_A , metadata={"""help""": """A csv or a json file containing the validation data."""} ) a__ = dataclasses.field( default=_A , metadata={"""help""": """The name of the task to train on."""} , ) a__ = dataclasses.field( default=_A , metadata={"""help""": """The list of labels for the task."""} ) @dataclasses.dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = dataclasses.field( metadata={"""help""": """The output directory where the model predictions and checkpoints will be written."""} ) a__ = dataclasses.field( default="""accuracy""" , metadata={"""help""": """The evaluation metric used for the task."""} ) a__ = dataclasses.field( default="""no""" , metadata={ """help""": """The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]""" } , ) a__ = dataclasses.field( default=10 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a__ = dataclasses.field( default=0.0 , metadata={ """help""": """How much the specified evaluation metric must improve to satisfy early stopping conditions.""" } , ) a__ = dataclasses.field( default=_A , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the confidence score."""} , ) a__ = dataclasses.field( default=_A , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the validation performance."""} , ) a__ = dataclasses.field( default=_A , metadata={"""help""": """Whether to fine-tune on labeled data after pseudo training."""} , ) a__ = dataclasses.field( default=0.0 , metadata={"""help""": """Confidence threshold for pseudo-labeled data filtering."""} , ) a__ = dataclasses.field( default=1_00 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a__ = dataclasses.field( default=_A , metadata={"""help""": """Random seed for initialization."""} , ) def a__ ( A_, A_, A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = datasets.concatenate_datasets([infer_input, infer_output], axis=1 ) if args.do_filter_by_confidence: __magic_name__ = dataset.filter(lambda A_ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 __magic_name__ = int(eval_result * len(A_ ) ) print(A_ ) __magic_name__ = dataset.sort("""probability""", reverse=A_ ) __magic_name__ = dataset.select(range(A_ ) ) __magic_name__ = dataset.remove_columns(["""label""", """probability"""] ) __magic_name__ = dataset.rename_column("""prediction""", """label""" ) __magic_name__ = dataset.map(lambda A_ : {"label": idalabel[example["label"]]} ) __magic_name__ = dataset.shuffle(seed=args.seed ) __magic_name__ = os.path.join(A_, f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(A_, index=A_ ) else: dataset.to_json(A_ ) def a__ ( A_, A_, A_, A_, **A_ ): '''simple docstring''' __magic_name__ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() __magic_name__ = STModelArguments(model_name_or_path=A_ ) __magic_name__ = STDataArguments(train_file=A_, infer_file=A_ ) __magic_name__ = STTrainingArguments(output_dir=A_ ) __magic_name__ = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(A_ ).items(): setattr(A_, A_, A_ ) for key, value in kwargs.items(): if hasattr(A_, A_ ): setattr(A_, A_, A_ ) # Sanity checks __magic_name__ = {} __magic_name__ = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None __magic_name__ = args.train_file __magic_name__ = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None __magic_name__ = args.eval_file for key in data_files: __magic_name__ = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: __magic_name__ = extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) __magic_name__ = f'''{args.output_dir}/self-train_iter-{{}}'''.format __magic_name__ = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=A_ ) os.makedirs(A_, exist_ok=A_ ) accelerator.wait_for_everyone() __magic_name__ = None __magic_name__ = None __magic_name__ = 0 __magic_name__ = False # Show the progress bar __magic_name__ = tqdm(range(args.max_selftrain_iterations ), disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0, int(args.max_selftrain_iterations ) ): __magic_name__ = data_dir_format(A_ ) assert os.path.exists(A_ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 __magic_name__ = os.path.join(A_, """stage-1""" ) __magic_name__ = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(A_, A_ ): arguments_dict.update({key: value} ) __magic_name__ = os.path.join(A_, """best-checkpoint""", A_ ) if os.path.exists(A_ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""", A_, A_, ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""", A_ ) finetune(**A_ ) accelerator.wait_for_everyone() assert os.path.exists(A_ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""", A_ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data __magic_name__ = os.path.join(A_, """best-checkpoint""" ) __magic_name__ = os.path.join(A_, """stage-2""" ) # Update arguments_dict __magic_name__ = model_path __magic_name__ = data_files["""train"""] __magic_name__ = current_output_dir __magic_name__ = os.path.join(A_, """best-checkpoint""", A_ ) if os.path.exists(A_ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""", A_, A_, ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""", A_ ) finetune(**A_ ) accelerator.wait_for_everyone() assert os.path.exists(A_ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""", A_ ) __magic_name__ = iteration __magic_name__ = data_dir_format(iteration + 1 ) __magic_name__ = AutoConfig.from_pretrained(os.path.join(A_, """best-checkpoint""" ) ) __magic_name__ = config.idalabel __magic_name__ = os.path.join(A_, """eval_results_best-checkpoint.json""" ) __magic_name__ = os.path.join(A_, """test_results_best-checkpoint.json""" ) assert os.path.exists(A_ ) with open(A_, """r""" ) as f: __magic_name__ = float(json.load(A_ )[args.eval_metric] ) __magic_name__ = os.path.join(A_, """infer_output_best-checkpoint.csv""" ) assert os.path.exists(A_ ) # Loading the dataset from local csv or json files. __magic_name__ = load_dataset(args.data_file_extension, data_files={"""data""": data_files["""infer"""]} )["""data"""] __magic_name__ = load_dataset("""csv""", data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(A_, exist_ok=A_ ) shutil.copy(A_, os.path.join(A_, f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(A_ ): shutil.copy(A_, os.path.join(A_, f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(A_, A_, A_, A_, A_, A_ ) accelerator.wait_for_everyone() __magic_name__ = os.path.join(A_, f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: __magic_name__ = eval_result if best_iteration is None: __magic_name__ = new_iteration __magic_name__ = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: __magic_name__ = new_iteration __magic_name__ = new_eval_result __magic_name__ = 0 else: if new_eval_result == best_eval_result: __magic_name__ = new_iteration __magic_name__ = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: __magic_name__ = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""", A_ ) logger.info("""Best evaluation result: %s = %f""", args.eval_metric, A_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(A_, f'''eval_results_iter-{iteration}.json''' ), os.path.join(A_, """eval_results_best-iteration.json""" ), ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""", args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""", args.eval_metric, A_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(A_, f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ), os.path.join(A_, """eval_results_best-iteration.json""" ), )
76
import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __lowerCAmelCase : str = { 'gwf-440k': { 'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-small-190k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-large-580k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt', 'sample_rate': 48000, 'sample_size': 131072, }, 'maestro-uncond-150k': { 'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'unlocked-uncond-250k': { 'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'honk-140k': { 'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, } def a__ ( A_, A_ ): '''simple docstring''' return torch.atana(A_, A_ ) / math.pi * 2 def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.sin(t * math.pi / 2 ) ** 2 __magic_name__ = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(A_, A_ ) class UpperCAmelCase_ ( _A ): '''simple docstring''' pass class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]: """simple docstring""" super().__init__() __magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 ) __magic_name__ = deepcopy(self.diffusion ) __magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MODELS_MAP[model_name]["""url"""] os.system(f'''wget {url} ./''' ) return f'''./{model_name}.ckpt''' __lowerCAmelCase : Optional[int] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', } __lowerCAmelCase : Optional[Any] = { '8': 'resnets.0', '9': 'attentions.0', '10': 'resnets.1', '11': 'attentions.1', '12': 'resnets.2', '13': 'attentions.2', } __lowerCAmelCase : Union[str, Any] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', '8': 'resnets.3', '9': 'attentions.3', '10': 'resnets.4', '11': 'attentions.4', '12': 'resnets.5', '13': 'attentions.5', } __lowerCAmelCase : int = { '0': 'resnets.0', '1': 'resnets.1', '2': 'resnets.2', '4': 'resnets.0', '5': 'resnets.1', '6': 'resnets.2', } __lowerCAmelCase : List[str] = { 'skip': 'conv_skip', 'main.0': 'conv_1', 'main.1': 'group_norm_1', 'main.3': 'conv_2', 'main.4': 'group_norm_2', } __lowerCAmelCase : int = { 'norm': 'group_norm', 'qkv_proj': ['query', 'key', 'value'], 'out_proj': ['proj_attn'], } def a__ ( A_ ): '''simple docstring''' if name.startswith("""skip""" ): return name.replace("""skip""", RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f'''ResConvBlock error with {name}''' ) return name.replace(name[:6], RES_CONV_MAP[name[:6]] ) def a__ ( A_ ): '''simple docstring''' for key, value in ATTN_MAP.items(): if name.startswith(A_ ) and not isinstance(A_, A_ ): return name.replace(A_, A_ ) elif name.startswith(A_ ): return [name.replace(A_, A_ ) for v in value] raise ValueError(f'''Attn error with {name}''' ) def a__ ( A_, A_=13 ): '''simple docstring''' __magic_name__ = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""", """time_proj""" ) __magic_name__ = 0 if string.startswith("""net.3.""" ): depth += 1 __magic_name__ = string[6:] elif string.startswith("""net.""" ): __magic_name__ = string[4:] while string.startswith("""main.7.""" ): depth += 1 __magic_name__ = string[7:] if string.startswith("""main.""" ): __magic_name__ = string[5:] # mid block if string[:2].isdigit(): __magic_name__ = string[:2] __magic_name__ = string[2:] else: __magic_name__ = string[0] __magic_name__ = string[1:] if depth == max_depth: __magic_name__ = MID_NUM_TO_LAYER[layer_num] __magic_name__ = """mid_block""" elif depth > 0 and int(A_ ) < 7: __magic_name__ = DOWN_NUM_TO_LAYER[layer_num] __magic_name__ = f'''down_blocks.{depth}''' elif depth > 0 and int(A_ ) > 7: __magic_name__ = UP_NUM_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - depth - 1}''' elif depth == 0: __magic_name__ = DEPTH_0_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' ) __magic_name__ = string_left[1:] if "resnets" in new_layer: __magic_name__ = convert_resconv_naming(A_ ) elif "attentions" in new_layer: __magic_name__ = convert_attn_naming(A_ ) __magic_name__ = new_string_left if not isinstance(A_, A_ ): __magic_name__ = prefix + """.""" + new_layer + """.""" + string_left else: __magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def a__ ( A_ ): '''simple docstring''' __magic_name__ = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue __magic_name__ = rename(A_ ) # check if we need to transform from Conv => Linear for attention if isinstance(A_, A_ ): __magic_name__ = transform_conv_attns(A_, A_, A_ ) else: __magic_name__ = v return new_state_dict def a__ ( A_, A_, A_ ): '''simple docstring''' if len(A_ ) == 1: if len(v.shape ) == 3: # weight __magic_name__ = v[:, :, 0] else: # bias __magic_name__ = v else: # qkv matrices __magic_name__ = v.shape[0] __magic_name__ = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __magic_name__ = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}''' __magic_name__ = download(A_ ) __magic_name__ = MODELS_MAP[model_name]["""sample_rate"""] __magic_name__ = MODELS_MAP[model_name]["""sample_size"""] __magic_name__ = Object() __magic_name__ = sample_size __magic_name__ = sample_rate __magic_name__ = 0 __magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ ) __magic_name__ = diffusers_model.state_dict() __magic_name__ = DiffusionUncond(A_ ) orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] ) __magic_name__ = orig_model.diffusion_ema.eval() __magic_name__ = orig_model.state_dict() __magic_name__ = rename_orig_weights(A_ ) __magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}''' assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}''' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}''' if key == "time_proj.weight": __magic_name__ = value.squeeze() __magic_name__ = value diffusers_model.load_state_dict(A_ ) __magic_name__ = 100 __magic_name__ = 33 __magic_name__ = IPNDMScheduler(num_train_timesteps=A_ ) __magic_name__ = torch.manual_seed(A_ ) __magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ ) __magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1] __magic_name__ = get_crash_schedule(A_ ) __magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ ) __magic_name__ = torch.manual_seed(33 ) __magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios __magic_name__ = sampling.iplms_sample(A_, A_, A_, {} ) __magic_name__ = generated.clamp(-1, 1 ) __magic_name__ = (generated - audio).abs().sum() __magic_name__ = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""", A_ ) print("""Diff max""", A_ ) assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/''' print(f'''Conversion for {model_name} successful!''' ) if __name__ == "__main__": __lowerCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') 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=None, type=str, required=True, help='Path to the output model.') __lowerCAmelCase : Union[str, Any] = parser.parse_args() main(args)
76
1
from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str: """simple docstring""" if tokenize_kwargs is None: __magic_name__ = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) __magic_name__ = truncation __magic_name__ = tokenize_kwargs __magic_name__ = {} if return_tensors is not None: __magic_name__ = return_tensors return preprocess_params, {}, postprocess_params def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]: """simple docstring""" __magic_name__ = self.framework __magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) return model_inputs def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str: """simple docstring""" __magic_name__ = self.model(**UpperCamelCase__ ) return model_outputs def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]: """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """lilt""" def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = classifier_dropout __magic_name__ = channel_shrink_ratio __magic_name__ = max_ad_position_embeddings
76
1
def a__ ( A_ ): '''simple docstring''' __magic_name__ = set() # To detect a back edge, keep track of vertices currently in the recursion stack __magic_name__ = set() return any( node not in visited and depth_first_search(A_, A_, A_, A_ ) for node in graph ) def a__ ( A_, A_, A_, A_ ): '''simple docstring''' visited.add(A_ ) rec_stk.add(A_ ) for node in graph[vertex]: if node not in visited: if depth_first_search(A_, A_, A_, A_ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(A_ ) return False if __name__ == "__main__": from doctest import testmod testmod()
76
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class UpperCAmelCase_ : '''simple docstring''' a__ = None def _lowercase ( self : Optional[int] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__ = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" ) feat_extract_first.to_json_file(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : str ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : Optional[int] ) -> Tuple: """simple docstring""" __magic_name__ = self.feature_extraction_class() self.assertIsNotNone(UpperCamelCase__ )
76
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def a__ ( A_ ): '''simple docstring''' __magic_name__ = 384 __magic_name__ = 7 if "tiny" in model_name: __magic_name__ = 96 __magic_name__ = (2, 2, 6, 2) __magic_name__ = (3, 6, 12, 24) elif "small" in model_name: __magic_name__ = 96 __magic_name__ = (2, 2, 18, 2) __magic_name__ = (3, 6, 12, 24) elif "base" in model_name: __magic_name__ = 128 __magic_name__ = (2, 2, 18, 2) __magic_name__ = (4, 8, 16, 32) __magic_name__ = 12 __magic_name__ = 512 elif "large" in model_name: __magic_name__ = 192 __magic_name__ = (2, 2, 18, 2) __magic_name__ = (6, 12, 24, 48) __magic_name__ = 12 __magic_name__ = 768 # set label information __magic_name__ = 150 __magic_name__ = """huggingface/label-files""" __magic_name__ = """ade20k-id2label.json""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ): v for k, v in idalabel.items()} __magic_name__ = {v: k for k, v in idalabel.items()} __magic_name__ = SwinConfig( embed_dim=A_, depths=A_, num_heads=A_, window_size=A_, out_features=["""stage1""", """stage2""", """stage3""", """stage4"""], ) __magic_name__ = UperNetConfig( backbone_config=A_, auxiliary_in_channels=A_, num_labels=A_, idalabel=A_, labelaid=A_, ) return config def a__ ( A_ ): '''simple docstring''' __magic_name__ = [] # fmt: off # stem rename_keys.append(("""backbone.patch_embed.projection.weight""", """backbone.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.projection.bias""", """backbone.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """backbone.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """backbone.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.stages.{i}.downsample.reduction.weight''', f'''backbone.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.weight''', f'''backbone.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.bias''', f'''backbone.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = dct.pop(A_ ) __magic_name__ = val def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __magic_name__ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __magic_name__ = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' ) __magic_name__ = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __magic_name__ = in_proj_weight[:dim, :] __magic_name__ = in_proj_bias[: dim] __magic_name__ = in_proj_weight[ dim : dim * 2, : ] __magic_name__ = in_proj_bias[ dim : dim * 2 ] __magic_name__ = in_proj_weight[ -dim :, : ] __magic_name__ = in_proj_bias[-dim :] # fmt: on def a__ ( A_ ): '''simple docstring''' __magic_name__ , __magic_name__ = x.shape __magic_name__ = x.reshape(A_, 4, in_channel // 4 ) __magic_name__ = x[:, [0, 2, 1, 3], :].transpose(1, 2 ).reshape(A_, A_ ) return x def a__ ( A_ ): '''simple docstring''' __magic_name__ , __magic_name__ = x.shape __magic_name__ = x.reshape(A_, in_channel // 4, 4 ) __magic_name__ = x[:, :, [0, 2, 1, 3]].transpose(1, 2 ).reshape(A_, A_ ) return x def a__ ( A_ ): '''simple docstring''' __magic_name__ = x.shape[0] __magic_name__ = x.reshape(4, in_channel // 4 ) __magic_name__ = x[[0, 2, 1, 3], :].transpose(0, 1 ).reshape(A_ ) return x def a__ ( A_ ): '''simple docstring''' __magic_name__ = x.shape[0] __magic_name__ = x.reshape(in_channel // 4, 4 ) __magic_name__ = x[:, [0, 2, 1, 3]].transpose(0, 1 ).reshape(A_ ) return x def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = { """upernet-swin-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth""", """upernet-swin-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth""", """upernet-swin-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth""", """upernet-swin-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth""", } __magic_name__ = model_name_to_url[model_name] __magic_name__ = torch.hub.load_state_dict_from_url(A_, map_location="""cpu""", file_name=A_ )[ """state_dict""" ] for name, param in state_dict.items(): print(A_, param.shape ) __magic_name__ = get_upernet_config(A_ ) __magic_name__ = UperNetForSemanticSegmentation(A_ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __magic_name__ = state_dict.pop(A_ ) if "bn" in key: __magic_name__ = key.replace("""bn""", """batch_norm""" ) __magic_name__ = val # rename keys __magic_name__ = create_rename_keys(A_ ) for src, dest in rename_keys: rename_key(A_, A_, A_ ) read_in_q_k_v(A_, config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __magic_name__ = reverse_correct_unfold_reduction_order(A_ ) if "norm" in key: __magic_name__ = reverse_correct_unfold_norm_order(A_ ) model.load_state_dict(A_ ) # verify on image __magic_name__ = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" __magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ).convert("""RGB""" ) __magic_name__ = SegformerImageProcessor() __magic_name__ = processor(A_, return_tensors="""pt""" ).pixel_values with torch.no_grad(): __magic_name__ = model(A_ ) __magic_name__ = outputs.logits print(logits.shape ) print("""First values of logits:""", logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __magic_name__ = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ) elif model_name == "upernet-swin-small": __magic_name__ = torch.tensor( [[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]] ) elif model_name == "upernet-swin-base": __magic_name__ = torch.tensor( [[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]] ) elif model_name == "upernet-swin-large": __magic_name__ = torch.tensor( [[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]] ) print("""Logits:""", outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3], A_, atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(A_ ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": __lowerCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-swin-tiny', type=str, choices=[F'''upernet-swin-{size}''' for size in ['tiny', 'small', 'base', 'large']], help='Name of the Swin + UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : Optional[int] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_A ): '''simple docstring''' a__ = ["""note_seq"""] def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""note_seq"""] ) @classmethod def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" requires_backends(cls , ["""note_seq"""] ) @classmethod def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int: """simple docstring""" requires_backends(cls , ["""note_seq"""] )
76
1
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 __lowerCAmelCase : str = namedtuple( '_TestCommandArgs', [ 'dataset', 'name', 'cache_dir', 'data_dir', 'all_configs', 'save_infos', 'ignore_verifications', 'force_redownload', 'clear_cache', ], defaults=[None, None, None, False, False, False, False, False], ) def a__ ( A_, A_ ): '''simple docstring''' return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def a__ ( A_ ): '''simple docstring''' __magic_name__ = _TestCommandArgs(dataset=A_, all_configs=A_, save_infos=A_ ) __magic_name__ = TestCommand(*A_ ) test_command.run() __magic_name__ = os.path.join(A_, """README.md""" ) assert os.path.exists(A_ ) __magic_name__ = DatasetInfosDict.from_directory(A_ ) __magic_name__ = 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""": 2351563, """num_examples""": 10000, }, { """name""": """validation""", """num_bytes""": 238418, """num_examples""": 1000, }, ], download_size=3940680, dataset_size=2589981, ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: __magic_name__ , __magic_name__ = 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
76
def a__ ( A_ ): '''simple docstring''' return " ".join( """""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
76
1
import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __lowerCAmelCase : str = { 'gwf-440k': { 'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-small-190k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-large-580k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt', 'sample_rate': 48000, 'sample_size': 131072, }, 'maestro-uncond-150k': { 'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'unlocked-uncond-250k': { 'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'honk-140k': { 'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, } def a__ ( A_, A_ ): '''simple docstring''' return torch.atana(A_, A_ ) / math.pi * 2 def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.sin(t * math.pi / 2 ) ** 2 __magic_name__ = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(A_, A_ ) class UpperCAmelCase_ ( _A ): '''simple docstring''' pass class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]: """simple docstring""" super().__init__() __magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 ) __magic_name__ = deepcopy(self.diffusion ) __magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MODELS_MAP[model_name]["""url"""] os.system(f'''wget {url} ./''' ) return f'''./{model_name}.ckpt''' __lowerCAmelCase : Optional[int] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', } __lowerCAmelCase : Optional[Any] = { '8': 'resnets.0', '9': 'attentions.0', '10': 'resnets.1', '11': 'attentions.1', '12': 'resnets.2', '13': 'attentions.2', } __lowerCAmelCase : Union[str, Any] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', '8': 'resnets.3', '9': 'attentions.3', '10': 'resnets.4', '11': 'attentions.4', '12': 'resnets.5', '13': 'attentions.5', } __lowerCAmelCase : int = { '0': 'resnets.0', '1': 'resnets.1', '2': 'resnets.2', '4': 'resnets.0', '5': 'resnets.1', '6': 'resnets.2', } __lowerCAmelCase : List[str] = { 'skip': 'conv_skip', 'main.0': 'conv_1', 'main.1': 'group_norm_1', 'main.3': 'conv_2', 'main.4': 'group_norm_2', } __lowerCAmelCase : int = { 'norm': 'group_norm', 'qkv_proj': ['query', 'key', 'value'], 'out_proj': ['proj_attn'], } def a__ ( A_ ): '''simple docstring''' if name.startswith("""skip""" ): return name.replace("""skip""", RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f'''ResConvBlock error with {name}''' ) return name.replace(name[:6], RES_CONV_MAP[name[:6]] ) def a__ ( A_ ): '''simple docstring''' for key, value in ATTN_MAP.items(): if name.startswith(A_ ) and not isinstance(A_, A_ ): return name.replace(A_, A_ ) elif name.startswith(A_ ): return [name.replace(A_, A_ ) for v in value] raise ValueError(f'''Attn error with {name}''' ) def a__ ( A_, A_=13 ): '''simple docstring''' __magic_name__ = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""", """time_proj""" ) __magic_name__ = 0 if string.startswith("""net.3.""" ): depth += 1 __magic_name__ = string[6:] elif string.startswith("""net.""" ): __magic_name__ = string[4:] while string.startswith("""main.7.""" ): depth += 1 __magic_name__ = string[7:] if string.startswith("""main.""" ): __magic_name__ = string[5:] # mid block if string[:2].isdigit(): __magic_name__ = string[:2] __magic_name__ = string[2:] else: __magic_name__ = string[0] __magic_name__ = string[1:] if depth == max_depth: __magic_name__ = MID_NUM_TO_LAYER[layer_num] __magic_name__ = """mid_block""" elif depth > 0 and int(A_ ) < 7: __magic_name__ = DOWN_NUM_TO_LAYER[layer_num] __magic_name__ = f'''down_blocks.{depth}''' elif depth > 0 and int(A_ ) > 7: __magic_name__ = UP_NUM_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - depth - 1}''' elif depth == 0: __magic_name__ = DEPTH_0_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' ) __magic_name__ = string_left[1:] if "resnets" in new_layer: __magic_name__ = convert_resconv_naming(A_ ) elif "attentions" in new_layer: __magic_name__ = convert_attn_naming(A_ ) __magic_name__ = new_string_left if not isinstance(A_, A_ ): __magic_name__ = prefix + """.""" + new_layer + """.""" + string_left else: __magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def a__ ( A_ ): '''simple docstring''' __magic_name__ = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue __magic_name__ = rename(A_ ) # check if we need to transform from Conv => Linear for attention if isinstance(A_, A_ ): __magic_name__ = transform_conv_attns(A_, A_, A_ ) else: __magic_name__ = v return new_state_dict def a__ ( A_, A_, A_ ): '''simple docstring''' if len(A_ ) == 1: if len(v.shape ) == 3: # weight __magic_name__ = v[:, :, 0] else: # bias __magic_name__ = v else: # qkv matrices __magic_name__ = v.shape[0] __magic_name__ = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __magic_name__ = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}''' __magic_name__ = download(A_ ) __magic_name__ = MODELS_MAP[model_name]["""sample_rate"""] __magic_name__ = MODELS_MAP[model_name]["""sample_size"""] __magic_name__ = Object() __magic_name__ = sample_size __magic_name__ = sample_rate __magic_name__ = 0 __magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ ) __magic_name__ = diffusers_model.state_dict() __magic_name__ = DiffusionUncond(A_ ) orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] ) __magic_name__ = orig_model.diffusion_ema.eval() __magic_name__ = orig_model.state_dict() __magic_name__ = rename_orig_weights(A_ ) __magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}''' assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}''' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}''' if key == "time_proj.weight": __magic_name__ = value.squeeze() __magic_name__ = value diffusers_model.load_state_dict(A_ ) __magic_name__ = 100 __magic_name__ = 33 __magic_name__ = IPNDMScheduler(num_train_timesteps=A_ ) __magic_name__ = torch.manual_seed(A_ ) __magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ ) __magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1] __magic_name__ = get_crash_schedule(A_ ) __magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ ) __magic_name__ = torch.manual_seed(33 ) __magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios __magic_name__ = sampling.iplms_sample(A_, A_, A_, {} ) __magic_name__ = generated.clamp(-1, 1 ) __magic_name__ = (generated - audio).abs().sum() __magic_name__ = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""", A_ ) print("""Diff max""", A_ ) assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/''' print(f'''Conversion for {model_name} successful!''' ) if __name__ == "__main__": __lowerCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') 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=None, type=str, required=True, help='Path to the output model.') __lowerCAmelCase : Union[str, Any] = parser.parse_args() main(args)
76
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = FunnelTokenizer a__ = FunnelTokenizerFast a__ = True a__ = True def _lowercase ( self : List[Any] ) -> str: """simple docstring""" super().setUp() __magic_name__ = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]: """simple docstring""" __magic_name__ = """UNwant\u00E9d,running""" __magic_name__ = """unwanted, running""" return input_text, output_text def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __magic_name__ = self.tokenizer_class(self.vocab_file ) __magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def _lowercase ( self : str ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: __magic_name__ = tokenizer("""UNwant\u00E9d,running""" ) __magic_name__ = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) __magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
76
1
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def a__ ( A_, A_, A_, A_ ): '''simple docstring''' if isinstance(A_, A_ ): __magic_name__ = np.full((len(A_ ), sequence_length, 2), A_ ) else: __magic_name__ = np.full((len(A_ ), sequence_length), A_ ) for i, tensor in enumerate(A_ ): if padding_side == "right": if isinstance(A_, A_ ): __magic_name__ = tensor[:sequence_length] else: __magic_name__ = tensor[:sequence_length] else: if isinstance(A_, A_ ): __magic_name__ = tensor[:sequence_length] else: __magic_name__ = tensor[:sequence_length] return out_tensor.tolist() def a__ ( A_ ): '''simple docstring''' __magic_name__ = ord(A_ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True __magic_name__ = unicodedata.category(A_ ) if cat.startswith("""P""" ): return True return False @dataclass class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = 42 a__ = True a__ = None a__ = None a__ = -1_00 a__ = "pt" def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple ) -> Union[str, Any]: """simple docstring""" import torch __magic_name__ = """label""" if """label""" in features[0].keys() else """labels""" __magic_name__ = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __magic_name__ = self.tokenizer.pad( UpperCamelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch __magic_name__ = torch.tensor(batch["""entity_ids"""] ).shape[1] __magic_name__ = self.tokenizer.padding_side if padding_side == "right": __magic_name__ = [ list(UpperCamelCase__ ) + [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase__ )) for label in labels ] else: __magic_name__ = [ [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase__ )) + list(UpperCamelCase__ ) for label in labels ] __magic_name__ = [feature["""ner_tags"""] for feature in features] __magic_name__ = padding_tensor(UpperCamelCase__ , -1 , UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = [feature["""original_entity_spans"""] for feature in features] __magic_name__ = padding_tensor(UpperCamelCase__ , (-1, -1) , UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = {k: torch.tensor(UpperCamelCase__ , dtype=torch.intaa ) for k, v in batch.items()} return batch
76
from collections import deque from .hash_table import HashTable class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(UpperCamelCase__ ) __magic_name__ = self.values[key] def _lowercase ( self : List[str] ) -> int: """simple docstring""" return ( sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values ) / self.size_table * self.charge_factor ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str: """simple docstring""" if not ( len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0 ): return key return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
76
1
def a__ ( A_ ): '''simple docstring''' return " ".join( """""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
76
# 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 json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def a__ ( A_ ): '''simple docstring''' __magic_name__ = botoa.client("""iam""" ) __magic_name__ = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) ) __magic_name__ = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), ) except iam_client.exceptions.EntityAlreadyExistsException: print(f'''role {role_name} already exists. Using existing one''' ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def a__ ( ): '''simple docstring''' __magic_name__ = _ask_options( """How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, ) __magic_name__ = None if credentials_configuration == 0: __magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" ) __magic_name__ = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __magic_name__ = _ask_field("""AWS Access Key ID: """ ) __magic_name__ = aws_access_key_id __magic_name__ = _ask_field("""AWS Secret Access Key: """ ) __magic_name__ = aws_secret_access_key __magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" ) __magic_name__ = aws_region __magic_name__ = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, ) if role_management == 0: __magic_name__ = _ask_field("""Enter your IAM role name: """ ) else: __magic_name__ = """accelerate_sagemaker_execution_role""" print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __magic_name__ = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_custom_docker_image: __magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() ) __magic_name__ = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_sagemaker_inputs_enabled: __magic_name__ = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), ) __magic_name__ = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_sagemaker_metrics_enabled: __magic_name__ = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), ) __magic_name__ = _ask_options( """What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, ) __magic_name__ = {} __magic_name__ = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) if use_dynamo: __magic_name__ = """dynamo_""" __magic_name__ = _ask_options( """Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) __magic_name__ = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) if use_custom_options: __magic_name__ = _ask_options( """Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", ) __magic_name__ = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __magic_name__ = _ask_options( A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" ) __magic_name__ = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __magic_name__ = _ask_field( """How many machines do you want use? [1]: """, A_, default=1, ) __magic_name__ = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
76
1
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput __lowerCAmelCase : Union[str, Any] = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Union[str, Any] , *UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Optional[int]=None , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = eval_examples __magic_name__ = post_process_function __magic_name__ = quant_trainer_args __magic_name__ = 128 # default number of calibration samples def _lowercase ( self : Any , UpperCamelCase__ : List[Any]=None ) -> int: """simple docstring""" if calib_dataset is None and self.calib_dataset is None: raise ValueError("""Trainer: calibration requires an calib_dataset.""" ) __magic_name__ = calib_dataset if calib_dataset is not None else self.calib_dataset __magic_name__ = self._remove_unused_columns(UpperCamelCase__ , description="""Calibration""" ) return DataLoader( UpperCamelCase__ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCamelCase__ , ) def _lowercase ( self : str , UpperCamelCase__ : Any=None ) -> Optional[int]: """simple docstring""" __magic_name__ = self.train_dataset if calib_dataset is None else calib_dataset __magic_name__ = self.get_calib_dataloader(UpperCamelCase__ ) __magic_name__ = self.model quant_trainer.configure_model(UpperCamelCase__ , self.quant_trainer_args , calib=UpperCamelCase__ ) model.eval() quant_trainer.enable_calibration(UpperCamelCase__ ) logger.info("""***** Running calibration *****""" ) logger.info(F''' Num examples = {self.calib_num}''' ) logger.info(F''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCamelCase__ ): # Prediction step __magic_name__ , __magic_name__ , __magic_name__ = self.prediction_step(UpperCamelCase__ , UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCamelCase__ , self.quant_trainer_args ) __magic_name__ = model def _lowercase ( self : int , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : str = "eval" ) -> int: """simple docstring""" __magic_name__ = self.eval_dataset if eval_dataset is None else eval_dataset __magic_name__ = self.get_eval_dataloader(UpperCamelCase__ ) __magic_name__ = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __magic_name__ = self.compute_metrics __magic_name__ = None __magic_name__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __magic_name__ = eval_loop( UpperCamelCase__ , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , ) finally: __magic_name__ = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: __magic_name__ = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions ) __magic_name__ = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): __magic_name__ = metrics.pop(UpperCamelCase__ ) self.log(UpperCamelCase__ ) else: __magic_name__ = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __magic_name__ = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCamelCase__ ) return metrics def _lowercase ( self : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : str=None , UpperCamelCase__ : str = "test" ) -> str: """simple docstring""" __magic_name__ = self.get_test_dataloader(UpperCamelCase__ ) # Temporarily disable metric computation, we will do it in the loop here. __magic_name__ = self.compute_metrics __magic_name__ = None __magic_name__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __magic_name__ = eval_loop( UpperCamelCase__ , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , ) finally: __magic_name__ = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output __magic_name__ = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions , """predict""" ) __magic_name__ = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): __magic_name__ = metrics.pop(UpperCamelCase__ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCamelCase__ ) def _lowercase ( self : Dict , UpperCamelCase__ : Optional[int]="./" ) -> Any: """simple docstring""" __magic_name__ = self.eval_dataset __magic_name__ = self.get_eval_dataloader(UpperCamelCase__ ) __magic_name__ = next(iter(UpperCamelCase__ ) ) # saving device - to make it consistent __magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) # convert to tuple __magic_name__ = tuple(v.to(UpperCamelCase__ ) for k, v in batch.items() ) logger.info("""Converting model to be onnx compatible""" ) from pytorch_quantization.nn import TensorQuantizer __magic_name__ = True __magic_name__ = self.model.to(UpperCamelCase__ ) model.eval() model.float() __magic_name__ = model.module if hasattr(UpperCamelCase__ , """module""" ) else model quant_trainer.configure_model(UpperCamelCase__ , self.quant_trainer_args ) __magic_name__ = os.path.join(UpperCamelCase__ , """model.onnx""" ) logger.info(F'''exporting model to {output_model_file}''' ) __magic_name__ = {0: """batch_size""", 1: """seq_len"""} torch.onnx.export( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , export_params=UpperCamelCase__ , opset_version=13 , do_constant_folding=UpperCamelCase__ , input_names=["""input_ids""", """attention_mask""", """token_type_ids"""] , output_names=["""output_start_logits""", """output_end_logits"""] , dynamic_axes={ """input_ids""": axes, """attention_mask""": axes, """token_type_ids""": axes, """output_start_logits""": axes, """output_end_logits""": axes, } , verbose=UpperCamelCase__ , ) logger.info("""onnx export finished""" )
76
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 __lowerCAmelCase : Dict = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD __magic_name__ = do_convert_rgb def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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, width). Got {size.keys()}''' ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __magic_name__ = 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.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: __magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
1
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) __lowerCAmelCase : Union[str, Any] = 'hf-internal-testing/tiny-random-bert' __lowerCAmelCase : List[Any] = os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert') __lowerCAmelCase : int = '9b8c223d42b2188cb49d29af482996f9d0f3e5a6' class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self : int ) -> Optional[int]: """simple docstring""" __magic_name__ = cached_file(UpperCamelCase__ , UpperCamelCase__ ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(UpperCamelCase__ ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) ) with open(os.path.join(UpperCamelCase__ , """refs""" , """main""" ) ) as f: __magic_name__ = f.read() self.assertEqual(UpperCamelCase__ , os.path.join(UpperCamelCase__ , """snapshots""" , UpperCamelCase__ , UpperCamelCase__ ) ) self.assertTrue(os.path.isfile(UpperCamelCase__ ) ) # File is cached at the same place the second time. __magic_name__ = cached_file(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) # Using a specific revision to test the full commit hash. __magic_name__ = cached_file(UpperCamelCase__ , UpperCamelCase__ , revision="""9b8c223""" ) self.assertEqual(UpperCamelCase__ , os.path.join(UpperCamelCase__ , """snapshots""" , UpperCamelCase__ , UpperCamelCase__ ) ) def _lowercase ( self : Tuple ) -> str: """simple docstring""" with self.assertRaisesRegex(UpperCamelCase__ , """is not a valid model identifier""" ): __magic_name__ = cached_file("""tiny-random-bert""" , UpperCamelCase__ ) with self.assertRaisesRegex(UpperCamelCase__ , """is not a valid git identifier""" ): __magic_name__ = cached_file(UpperCamelCase__ , UpperCamelCase__ , revision="""aaaa""" ) with self.assertRaisesRegex(UpperCamelCase__ , """does not appear to have a file named""" ): __magic_name__ = cached_file(UpperCamelCase__ , """conf""" ) def _lowercase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex(UpperCamelCase__ , """does not appear to have a file named""" ): __magic_name__ = cached_file(UpperCamelCase__ , """conf""" ) with open(os.path.join(UpperCamelCase__ , """refs""" , """main""" ) ) as f: __magic_name__ = f.read() self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase__ , """.no_exist""" , UpperCamelCase__ , """conf""" ) ) ) __magic_name__ = cached_file(UpperCamelCase__ , """conf""" , _raise_exceptions_for_missing_entries=UpperCamelCase__ ) self.assertIsNone(UpperCamelCase__ ) __magic_name__ = cached_file(UpperCamelCase__ , """conf""" , local_files_only=UpperCamelCase__ , _raise_exceptions_for_missing_entries=UpperCamelCase__ ) self.assertIsNone(UpperCamelCase__ ) __magic_name__ = mock.Mock() __magic_name__ = 500 __magic_name__ = {} __magic_name__ = HTTPError __magic_name__ = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("""requests.Session.request""" , return_value=UpperCamelCase__ ) as mock_head: __magic_name__ = cached_file(UpperCamelCase__ , """conf""" , _raise_exceptions_for_connection_errors=UpperCamelCase__ ) self.assertIsNone(UpperCamelCase__ ) # This check we did call the fake head request mock_head.assert_called() def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" self.assertTrue(has_file("""hf-internal-testing/tiny-bert-pt-only""" , UpperCamelCase__ ) ) self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only""" , UpperCamelCase__ ) ) self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only""" , UpperCamelCase__ ) ) def _lowercase ( self : Union[str, Any] ) -> int: """simple docstring""" self.assertIsNone(get_file_from_repo("""bert-base-cased""" , """ahah.txt""" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(UpperCamelCase__ , """is not a valid model identifier""" ): get_file_from_repo("""bert-base-case""" , UpperCamelCase__ ) # The function raises if the revision does not exist. with self.assertRaisesRegex(UpperCamelCase__ , """is not a valid git identifier""" ): get_file_from_repo("""bert-base-cased""" , UpperCamelCase__ , revision="""ahaha""" ) __magic_name__ = get_file_from_repo("""bert-base-cased""" , UpperCamelCase__ ) # The name is the cached name which is not very easy to test, so instead we load the content. __magic_name__ = json.loads(open(UpperCamelCase__ , """r""" ).read() ) self.assertEqual(config["""hidden_size"""] , 768 ) def _lowercase ( self : Any ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ = Path(UpperCamelCase__ ) / """a.txt""" filename.touch() self.assertEqual(get_file_from_repo(UpperCamelCase__ , """a.txt""" ) , str(UpperCamelCase__ ) ) self.assertIsNone(get_file_from_repo(UpperCamelCase__ , """b.txt""" ) )
76
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Any ) -> Any: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Tuple ) -> Any: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , ) def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple: """simple docstring""" __magic_name__ = NystromformerModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str: """simple docstring""" __magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a__ = False a__ = False def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = NystromformerModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : str ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def _lowercase ( self : str ) -> Tuple: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) ) @slow def _lowercase ( self : int ) -> str: """simple docstring""" __magic_name__ = """the [MASK] of Belgium is Brussels""" __magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" ) with torch.no_grad(): __magic_name__ = model(encoding.input_ids ).logits __magic_name__ = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
76
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Union[str, Any] = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """cvt""" def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = num_channels __magic_name__ = patch_sizes __magic_name__ = patch_stride __magic_name__ = patch_padding __magic_name__ = embed_dim __magic_name__ = num_heads __magic_name__ = depth __magic_name__ = mlp_ratio __magic_name__ = attention_drop_rate __magic_name__ = drop_rate __magic_name__ = drop_path_rate __magic_name__ = qkv_bias __magic_name__ = cls_token __magic_name__ = qkv_projection_method __magic_name__ = kernel_qkv __magic_name__ = padding_kv __magic_name__ = stride_kv __magic_name__ = padding_q __magic_name__ = stride_q __magic_name__ = initializer_range __magic_name__ = layer_norm_eps
76
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Dict = logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] = { 'huggingface/autoformer-tourism-monthly': 'https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json', } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """autoformer""" a__ = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", """num_hidden_layers""": """encoder_layers""", } def __init__( self : Optional[int] , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : str = "student_t" , UpperCamelCase__ : str = "nll" , UpperCamelCase__ : int = 1 , UpperCamelCase__ : List[int] = [1, 2, 3, 4, 5, 6, 7] , UpperCamelCase__ : bool = True , UpperCamelCase__ : int = 0 , UpperCamelCase__ : int = 0 , UpperCamelCase__ : int = 0 , UpperCamelCase__ : int = 0 , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : int = 64 , UpperCamelCase__ : int = 2 , UpperCamelCase__ : int = 2 , UpperCamelCase__ : int = 2 , UpperCamelCase__ : int = 2 , UpperCamelCase__ : int = 32 , UpperCamelCase__ : int = 32 , UpperCamelCase__ : str = "gelu" , UpperCamelCase__ : float = 0.1 , UpperCamelCase__ : float = 0.1 , UpperCamelCase__ : float = 0.1 , UpperCamelCase__ : float = 0.1 , UpperCamelCase__ : float = 0.1 , UpperCamelCase__ : int = 100 , UpperCamelCase__ : float = 0.02 , UpperCamelCase__ : bool = True , UpperCamelCase__ : str=True , UpperCamelCase__ : int = 10 , UpperCamelCase__ : int = 25 , UpperCamelCase__ : int = 3 , **UpperCamelCase__ : Any , ) -> str: """simple docstring""" __magic_name__ = prediction_length __magic_name__ = context_length if context_length is not None else prediction_length __magic_name__ = distribution_output __magic_name__ = loss __magic_name__ = input_size __magic_name__ = num_time_features __magic_name__ = lags_sequence __magic_name__ = scaling __magic_name__ = num_dynamic_real_features __magic_name__ = num_static_real_features __magic_name__ = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(UpperCamelCase__ ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __magic_name__ = cardinality else: __magic_name__ = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(UpperCamelCase__ ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __magic_name__ = embedding_dimension else: __magic_name__ = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __magic_name__ = num_parallel_samples # Transformer architecture configuration __magic_name__ = input_size * len(self.lags_sequence ) + self._number_of_features __magic_name__ = d_model __magic_name__ = encoder_attention_heads __magic_name__ = decoder_attention_heads __magic_name__ = encoder_ffn_dim __magic_name__ = decoder_ffn_dim __magic_name__ = encoder_layers __magic_name__ = decoder_layers __magic_name__ = dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = encoder_layerdrop __magic_name__ = decoder_layerdrop __magic_name__ = activation_function __magic_name__ = init_std __magic_name__ = use_cache # Autoformer __magic_name__ = label_length __magic_name__ = moving_average __magic_name__ = autocorrelation_factor super().__init__(is_encoder_decoder=UpperCamelCase__ , **UpperCamelCase__ ) @property def _lowercase ( self : List[str] ) -> int: """simple docstring""" return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
76
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase : List[str] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[Any] = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys __lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """lilt""" def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = classifier_dropout __magic_name__ = channel_shrink_ratio __magic_name__ = max_ad_position_embeddings
76
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""projector.weight"""] __magic_name__ = downstream_dict["""projector.bias"""] __magic_name__ = downstream_dict["""model.post_net.linear.weight"""] __magic_name__ = downstream_dict["""model.post_net.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""model.linear.weight"""] __magic_name__ = downstream_dict["""model.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""connector.weight"""] __magic_name__ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __magic_name__ = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] __magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] __magic_name__ = downstream_dict["""objective.W"""] return model @torch.no_grad() def a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = torch.load(A_, map_location="""cpu""" ) __magic_name__ = checkpoint["""Downstream"""] __magic_name__ = WavaVecaConfig.from_pretrained(A_ ) __magic_name__ = WavaVecaFeatureExtractor.from_pretrained( A_, return_attention_mask=A_, do_normalize=A_ ) __magic_name__ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): __magic_name__ = convert_classification(A_, A_, A_ ) elif arch.endswith("""ForAudioFrameClassification""" ): __magic_name__ = convert_diarization(A_, A_, A_ ) elif arch.endswith("""ForXVector""" ): __magic_name__ = convert_xvector(A_, A_, A_ ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: __magic_name__ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(A_ ) hf_model.save_pretrained(A_ ) if __name__ == "__main__": __lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __lowerCAmelCase : str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
76
1
def a__ ( A_ ): '''simple docstring''' assert column_title.isupper() __magic_name__ = 0 __magic_name__ = len(A_ ) - 1 __magic_name__ = 0 while index >= 0: __magic_name__ = (ord(column_title[index] ) - 64) * pow(26, A_ ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
76
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a__ ( A_, A_ ): '''simple docstring''' assert isinstance(A_, A_ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read() _check_text_dataset(A_, A_ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""", [str, list] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if issubclass(A_, A_ ): __magic_name__ = text_path elif issubclass(A_, A_ ): __magic_name__ = [text_path] __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) def a__ ( A_, A_, A_=("train",) ): '''simple docstring''' assert isinstance(A_, A_ ) for split in splits: __magic_name__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if split: __magic_name__ = {split: text_path} else: __magic_name__ = """train""" __magic_name__ = {"""train""": text_path, """test""": text_path} __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
76
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : str = { 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """mra""" def __init__( self : str , UpperCamelCase__ : Dict=5_0265 , UpperCamelCase__ : List[str]=768 , UpperCamelCase__ : int=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Optional[Any]=1 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : Tuple=1E-5 , UpperCamelCase__ : Optional[Any]="absolute" , UpperCamelCase__ : Tuple=4 , UpperCamelCase__ : List[Any]="full" , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[str]=2 , **UpperCamelCase__ : List[Any] , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = initializer_range __magic_name__ = type_vocab_size __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = block_per_row __magic_name__ = approx_mode __magic_name__ = initial_prior_first_n_blocks __magic_name__ = initial_prior_diagonal_n_blocks
76
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, 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, logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 256} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" __magic_name__ = get_size_dict(UpperCamelCase__ ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = 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. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
1
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __lowerCAmelCase : List[str] = logging.get_logger(__name__) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(A_ ) == len(A_ ), f'''{len(A_ )} != {len(A_ )}''' dest_layers.load_state_dict(layers_to_copy.state_dict() ) __lowerCAmelCase : int = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __lowerCAmelCase : List[str] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def a__ ( A_, A_ ): '''simple docstring''' try: __magic_name__ = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first''' f''' {n_student}''' ) return list(range(A_ ) ) def a__ ( A_, A_ ): '''simple docstring''' if n_student > n_teacher: raise ValueError(f'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''' ) elif n_teacher == n_student: return list(range(A_ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def a__ ( A_, A_ = "student", A_ = None, A_ = None, A_=False, A_=None, A_=None, **A_, ): '''simple docstring''' __magic_name__ = """encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.""" assert (e is not None) or (d is not None), _msg if isinstance(A_, A_ ): AutoTokenizer.from_pretrained(A_ ).save_pretrained(A_ ) # purely for convenience __magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(A_ ).eval() else: assert isinstance(A_, A_ ), f'''teacher must be a model or string got type {type(A_ )}''' __magic_name__ = teacher.config.to_diff_dict() try: __magic_name__ , __magic_name__ = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __magic_name__ = teacher_e if d is None: __magic_name__ = teacher_d init_kwargs.update({"""encoder_layers""": e, """decoder_layers""": d} ) except AttributeError: # T5 if hasattr(teacher.config, """num_encoder_layers""" ): __magic_name__ , __magic_name__ = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __magic_name__ , __magic_name__ = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __magic_name__ = teacher_e if d is None: __magic_name__ = teacher_d if hasattr(teacher.config, """num_encoder_layers""" ): init_kwargs.update({"""num_encoder_layers""": e, """num_decoder_layers""": d} ) else: init_kwargs.update({"""num_layers""": e, """num_decoder_layers""": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(A_ ) # Copy weights __magic_name__ = teacher.config_class(**A_ ) __magic_name__ = AutoModelForSeqaSeqLM.from_config(A_ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __magic_name__ = student.load_state_dict(teacher.state_dict(), strict=A_ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __magic_name__ , __magic_name__ = list(range(A_ ) ), list(range(A_ ) ) logger.info( f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to''' f''' {save_path}''' ) student.save_pretrained(A_ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __magic_name__ = pick_layers_to_copy(A_, A_ ) if d_layers_to_copy is None: __magic_name__ = pick_layers_to_copy(A_, A_ ) try: if hasattr( A_, """prophetnet""" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers, student.prophetnet.encoder.layers, A_ ) copy_layers(teacher.prophetnet.decoder.layers, student.prophetnet.decoder.layers, A_ ) else: copy_layers(teacher.model.encoder.layers, student.model.encoder.layers, A_ ) copy_layers(teacher.model.decoder.layers, student.model.decoder.layers, A_ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block, student.encoder.block, A_ ) copy_layers(teacher.decoder.block, student.decoder.block, A_ ) logger.info( f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''' ) __magic_name__ = { """teacher_type""": teacher.config.model_type, """copied_encoder_layers""": e_layers_to_copy, """copied_decoder_layers""": d_layers_to_copy, } student.save_pretrained(A_ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
76
import math def a__ ( A_, A_ = 0, A_ = 0 ): '''simple docstring''' __magic_name__ = end or len(A_ ) for i in range(A_, A_ ): __magic_name__ = i __magic_name__ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __magic_name__ = array[temp_index - 1] temp_index -= 1 __magic_name__ = temp_index_value return array def a__ ( A_, A_, A_ ): # Max Heap '''simple docstring''' __magic_name__ = index __magic_name__ = 2 * index + 1 # Left Node __magic_name__ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __magic_name__ = left_index if right_index < heap_size and array[largest] < array[right_index]: __magic_name__ = right_index if largest != index: __magic_name__ , __magic_name__ = array[largest], array[index] heapify(A_, A_, A_ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = len(A_ ) for i in range(n // 2, -1, -1 ): heapify(A_, A_, A_ ) for i in range(n - 1, 0, -1 ): __magic_name__ , __magic_name__ = array[0], array[i] heapify(A_, 0, A_ ) return array def a__ ( A_, A_, A_, A_ ): '''simple docstring''' 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 a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = low __magic_name__ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __magic_name__ , __magic_name__ = array[j], array[i] i += 1 def a__ ( A_ ): '''simple docstring''' if len(A_ ) == 0: return array __magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) ) __magic_name__ = 16 return intro_sort(A_, 0, len(A_ ), A_, A_ ) def a__ ( A_, A_, A_, A_, A_ ): '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(A_ ) max_depth -= 1 __magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 ) __magic_name__ = partition(A_, A_, A_, A_ ) intro_sort(A_, A_, A_, A_, A_ ) __magic_name__ = p return insertion_sort(A_, A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip() __lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')] print(sort(unsorted))
76
1
__lowerCAmelCase : Union[str, Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def a__ ( ): '''simple docstring''' __magic_name__ = input("""Enter message: """ ) __magic_name__ = input("""Enter key [alphanumeric]: """ ) __magic_name__ = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): __magic_name__ = """encrypt""" __magic_name__ = encrypt_message(A_, A_ ) elif mode.lower().startswith("""d""" ): __magic_name__ = """decrypt""" __magic_name__ = decrypt_message(A_, A_ ) print(f'''\n{mode.title()}ed message:''' ) print(A_ ) def a__ ( A_, A_ ): '''simple docstring''' return translate_message(A_, A_, """encrypt""" ) def a__ ( A_, A_ ): '''simple docstring''' return translate_message(A_, A_, """decrypt""" ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = [] __magic_name__ = 0 __magic_name__ = key.upper() for symbol in message: __magic_name__ = 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(A_ ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(A_ ): __magic_name__ = 0 else: translated.append(A_ ) return "".join(A_ ) if __name__ == "__main__": main()
76
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) __magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ ) if matches: __magic_name__ = float(matches[1] ) __magic_name__ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __magic_name__ = 1001 __magic_name__ = """imagenet-1k-id2label.json""" __magic_name__ = """huggingface/label-files""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()} __magic_name__ = """background""" __magic_name__ = idalabel __magic_name__ = {v: k for k, v in idalabel.items()} return config def a__ ( ): '''simple docstring''' __magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" __magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ) return im @torch.no_grad() def a__ ( A_, A_, A_, A_=False ): '''simple docstring''' __magic_name__ = get_mobilenet_va_config(A_ ) # Load 🤗 model __magic_name__ = MobileNetVaForImageClassification(A_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(A_, A_, A_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __magic_name__ = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, ) __magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" ) __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __magic_name__ = None if expected_logits is not None: assert torch.allclose(logits[0, :3], A_, atol=1e-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if push_to_hub: print("""Pushing to the hub...""" ) __magic_name__ = """google/""" + model_name image_processor.push_to_hub(A_ ) model.push_to_hub(A_ ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : str = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
76
1
import logging from transformers.configuration_utils import PretrainedConfig __lowerCAmelCase : List[Any] = logging.getLogger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """masked_bert""" def __init__( self : Optional[int] , UpperCamelCase__ : Optional[int]=3_0522 , UpperCamelCase__ : Union[str, Any]=768 , UpperCamelCase__ : Optional[int]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : int=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : Optional[Any]=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="topK" , UpperCamelCase__ : str="constant" , UpperCamelCase__ : int=0.0 , **UpperCamelCase__ : Any , ) -> Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = pruning_method __magic_name__ = mask_init __magic_name__ = mask_scale
76
import collections import importlib.util import os import re from pathlib import Path __lowerCAmelCase : int = 'src/transformers' # Matches is_xxx_available() __lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} __lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", __lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], __lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo __lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: __lowerCAmelCase : int = re.compile(R'^\s*try:') # Catches a line with else: __lowerCAmelCase : Tuple = re.compile(R'^\s*else:') def a__ ( A_ ): '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None __magic_name__ = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def a__ ( A_ ): '''simple docstring''' with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f: __magic_name__ = f.readlines() __magic_name__ = 0 while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure __magic_name__ = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: __magic_name__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): __magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0] __magic_name__ = re.findall("""\[([^\]]+)\]""", A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue __magic_name__ = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: __magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): __magic_name__ = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: __magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: __magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 __magic_name__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __magic_name__ = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 __magic_name__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def a__ ( A_, A_ ): '''simple docstring''' def find_duplicates(A_ ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __magic_name__ = [] for key in import_dict_objects.keys(): __magic_name__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) __magic_name__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __magic_name__ = """base imports""" if key == """none""" else f'''{key} backend''' errors.append(f'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def a__ ( ): '''simple docstring''' __magic_name__ = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: __magic_name__ = os.path.join(A_, """__init__.py""" ) __magic_name__ = parse_init(A_ ) if objects is not None: __magic_name__ = analyze_results(*A_ ) if len(A_ ) > 0: __magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("""\n""".join(A_ ) ) if len(A_ ) > 0: raise ValueError("""\n\n""".join(A_ ) ) def a__ ( ): '''simple docstring''' __magic_name__ = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0: continue __magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) ) __magic_name__ = short_path.replace(os.path.sep, """.""" ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue __magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) ) __magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(A_ ) return submodules __lowerCAmelCase : Dict = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def a__ ( ): '''simple docstring''' __magic_name__ = importlib.util.spec_from_file_location( """transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) __magic_name__ = spec.loader.load_module() __magic_name__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: __magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registered in the main init of Transformers:\n""" f'''{list_of_modules}\n''' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
76
1
from typing import List import numpy as np def a__ ( A_ ): '''simple docstring''' __magic_name__ = {key: len(A_ ) for key, value in gen_kwargs.items() if isinstance(A_, A_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( """Sharding is ambiguous for this dataset: """ + """we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n""" + """\n""".join(f'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() ) + """\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, """ + """and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.""" ) ) __magic_name__ = max(lists_lengths.values(), default=0 ) return max(1, A_ ) def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = [] for group_idx in range(A_ ): __magic_name__ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __magic_name__ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __magic_name__ = range(A_, start + num_shards_to_add ) shards_indices_per_group.append(A_ ) return shards_indices_per_group def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = _number_of_shards_in_gen_kwargs(A_ ) if num_shards == 1: return [dict(A_ )] else: __magic_name__ = _distribute_shards(num_shards=A_, max_num_jobs=A_ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(A_, A_ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(A_ ) ) ] def a__ ( A_ ): '''simple docstring''' return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key], A_ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = {len(A_ ) for value in gen_kwargs.values() if isinstance(A_, A_ )} __magic_name__ = {} for size in list_sizes: __magic_name__ = list(range(A_ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __magic_name__ = dict(A_ ) for key, value in shuffled_kwargs.items(): if isinstance(A_, A_ ): __magic_name__ = [value[i] for i in indices_per_size[len(A_ )]] return shuffled_kwargs
76
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[Any] = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """sew-d""" def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) __magic_name__ = hidden_size __magic_name__ = feat_extract_norm __magic_name__ = feat_extract_activation __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = conv_bias __magic_name__ = num_conv_pos_embeddings __magic_name__ = num_conv_pos_embedding_groups __magic_name__ = len(self.conv_dim ) __magic_name__ = num_hidden_layers __magic_name__ = intermediate_size __magic_name__ = squeeze_factor __magic_name__ = max_position_embeddings __magic_name__ = position_buckets __magic_name__ = share_att_key __magic_name__ = relative_attention __magic_name__ = norm_rel_ebd __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = hidden_act __magic_name__ = num_attention_heads __magic_name__ = hidden_dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = feat_proj_dropout __magic_name__ = final_dropout __magic_name__ = layer_norm_eps __magic_name__ = feature_layer_norm_eps __magic_name__ = initializer_range __magic_name__ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __magic_name__ = apply_spec_augment __magic_name__ = mask_time_prob __magic_name__ = mask_time_length __magic_name__ = mask_time_min_masks __magic_name__ = mask_feature_prob __magic_name__ = mask_feature_length __magic_name__ = mask_feature_min_masks # ctc loss __magic_name__ = ctc_loss_reduction __magic_name__ = ctc_zero_infinity # sequence classification __magic_name__ = use_weighted_layer_sum __magic_name__ = classifier_proj_size @property def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
76
1
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Any = { 'linear': get_linear_schedule_with_warmup, 'cosine': get_cosine_schedule_with_warmup, 'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup, 'polynomial': get_polynomial_decay_schedule_with_warmup, 'constant': get_constant_schedule, 'constant_w_warmup': get_constant_schedule_with_warmup, } class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Optional[int] , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : str=None , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) if config is None: assert isinstance(self.model , UpperCamelCase__ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F''' {self.model.__class__}''' ) __magic_name__ = self.model.config else: __magic_name__ = config __magic_name__ = data_args __magic_name__ = self.config.tgt_vocab_size if isinstance(self.config , UpperCamelCase__ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' """ padding..""" ) if self.args.label_smoothing == 0: __magic_name__ = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __magic_name__ = label_smoothed_nll_loss def _lowercase ( self : int , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" if self.optimizer is None: __magic_name__ = ["""bias""", """LayerNorm.weight"""] __magic_name__ = [ { """params""": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], """weight_decay""": self.args.weight_decay, }, { """params""": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] __magic_name__ = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __magic_name__ = Adafactor __magic_name__ = {"""scale_parameter""": False, """relative_step""": False} else: __magic_name__ = AdamW __magic_name__ = { """betas""": (self.args.adam_betaa, self.args.adam_betaa), """eps""": self.args.adam_epsilon, } __magic_name__ = self.args.learning_rate if self.sharded_ddp: __magic_name__ = OSS( params=UpperCamelCase__ , optim=UpperCamelCase__ , **UpperCamelCase__ , ) else: __magic_name__ = optimizer_cls(UpperCamelCase__ , **UpperCamelCase__ ) if self.lr_scheduler is None: __magic_name__ = self._get_lr_scheduler(UpperCamelCase__ ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict ) -> Dict: """simple docstring""" __magic_name__ = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __magic_name__ = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __magic_name__ = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __magic_name__ = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=UpperCamelCase__ ) return scheduler def _lowercase ( self : Optional[Any] ) -> Optional[torch.utils.data.Sampler]: """simple docstring""" if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : int , UpperCamelCase__ : str ) -> Optional[int]: """simple docstring""" if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __magic_name__ = model(**UpperCamelCase__ , use_cache=UpperCamelCase__ )[0] __magic_name__ = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __magic_name__ , __magic_name__ = model(**UpperCamelCase__ , labels=UpperCamelCase__ , use_cache=UpperCamelCase__ )[:2] else: # compute label smoothed loss __magic_name__ = model(**UpperCamelCase__ , use_cache=UpperCamelCase__ )[0] __magic_name__ = torch.nn.functional.log_softmax(UpperCamelCase__ , dim=-1 ) __magic_name__ , __magic_name__ = self.loss_fn(UpperCamelCase__ , UpperCamelCase__ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _lowercase ( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Tuple: """simple docstring""" __magic_name__ = inputs.pop("""labels""" ) __magic_name__ , __magic_name__ = self._compute_loss(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return loss def _lowercase ( self : List[Any] , UpperCamelCase__ : nn.Module , UpperCamelCase__ : Dict[str, Union[torch.Tensor, Any]] , UpperCamelCase__ : bool , UpperCamelCase__ : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: """simple docstring""" __magic_name__ = self._prepare_inputs(UpperCamelCase__ ) __magic_name__ = { """max_length""": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, """num_beams""": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __magic_name__ = self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **UpperCamelCase__ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __magic_name__ = self._pad_tensors_to_max_len(UpperCamelCase__ , gen_kwargs["""max_length"""] ) __magic_name__ = inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data __magic_name__ , __magic_name__ = self._compute_loss(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __magic_name__ = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __magic_name__ = self._pad_tensors_to_max_len(UpperCamelCase__ , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] ) -> Dict: """simple docstring""" __magic_name__ = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" F''' padded to `max_length`={max_length}''' ) __magic_name__ = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __magic_name__ = tensor return padded_tensor
76
import math import random def a__ ( A_, A_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __lowerCAmelCase : Union[str, Any] = 0.02 def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = float(2 * (random.randint(1, 100 )) - 1 ) for _ in range(A_ ): # Forward propagation __magic_name__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __magic_name__ = (expected / 100) - layer_a # Error delta __magic_name__ = layer_1_error * sigmoid_function(A_, A_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : List[Any] = int(input('Expected value: ')) __lowerCAmelCase : Tuple = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
76
1
import math import random def a__ ( A_, A_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __lowerCAmelCase : Union[str, Any] = 0.02 def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = float(2 * (random.randint(1, 100 )) - 1 ) for _ in range(A_ ): # Forward propagation __magic_name__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __magic_name__ = (expected / 100) - layer_a # Error delta __magic_name__ = layer_1_error * sigmoid_function(A_, A_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : List[Any] = int(input('Expected value: ')) __lowerCAmelCase : Tuple = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
76
import os import sys __lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowerCAmelCase : Union[str, Any] = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoConfig.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoTokenizer.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModel.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModel.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
76
1
from ...configuration_utils import PretrainedConfig __lowerCAmelCase : List[str] = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """tapas""" def __init__( self : Optional[Any] , UpperCamelCase__ : Union[str, Any]=3_0522 , UpperCamelCase__ : List[str]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Any=3072 , UpperCamelCase__ : Optional[Any]="gelu" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Tuple=1024 , UpperCamelCase__ : Union[str, Any]=[3, 256, 256, 2, 256, 256, 10] , UpperCamelCase__ : Optional[Any]=0.02 , UpperCamelCase__ : int=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : int=10.0 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Tuple=1.0 , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : int=1.0 , UpperCamelCase__ : Any=False , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[int]=1.0 , UpperCamelCase__ : int=1.0 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : List[Any]="ratio" , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : str=64 , UpperCamelCase__ : Any=32 , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : int=True , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : str=None , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : Dict , ) -> Tuple: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_sizes __magic_name__ = initializer_range __magic_name__ = layer_norm_eps # Fine-tuning task hyperparameters __magic_name__ = positive_label_weight __magic_name__ = num_aggregation_labels __magic_name__ = aggregation_loss_weight __magic_name__ = use_answer_as_supervision __magic_name__ = answer_loss_importance __magic_name__ = use_normalized_answer_loss __magic_name__ = huber_loss_delta __magic_name__ = temperature __magic_name__ = aggregation_temperature __magic_name__ = use_gumbel_for_cells __magic_name__ = use_gumbel_for_aggregation __magic_name__ = average_approximation_function __magic_name__ = cell_selection_preference __magic_name__ = answer_loss_cutoff __magic_name__ = max_num_rows __magic_name__ = max_num_columns __magic_name__ = average_logits_per_cell __magic_name__ = select_one_column __magic_name__ = allow_empty_column_selection __magic_name__ = init_cell_selection_weights_to_zero __magic_name__ = reset_position_index_per_cell __magic_name__ = disable_per_token_loss # Aggregation hyperparameters __magic_name__ = aggregation_labels __magic_name__ = no_aggregation_label_index if isinstance(self.aggregation_labels , UpperCamelCase__ ): __magic_name__ = {int(UpperCamelCase__ ): v for k, v in aggregation_labels.items()}
76
from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str: """simple docstring""" if tokenize_kwargs is None: __magic_name__ = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) __magic_name__ = truncation __magic_name__ = tokenize_kwargs __magic_name__ = {} if return_tensors is not None: __magic_name__ = return_tensors return preprocess_params, {}, postprocess_params def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]: """simple docstring""" __magic_name__ = self.framework __magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) return model_inputs def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str: """simple docstring""" __magic_name__ = self.model(**UpperCamelCase__ ) return model_outputs def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]: """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
76
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase : Dict = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[str] = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __lowerCAmelCase : str = { 'gwf-440k': { 'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-small-190k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-large-580k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt', 'sample_rate': 48000, 'sample_size': 131072, }, 'maestro-uncond-150k': { 'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'unlocked-uncond-250k': { 'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'honk-140k': { 'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, } def a__ ( A_, A_ ): '''simple docstring''' return torch.atana(A_, A_ ) / math.pi * 2 def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.sin(t * math.pi / 2 ) ** 2 __magic_name__ = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(A_, A_ ) class UpperCAmelCase_ ( _A ): '''simple docstring''' pass class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]: """simple docstring""" super().__init__() __magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 ) __magic_name__ = deepcopy(self.diffusion ) __magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MODELS_MAP[model_name]["""url"""] os.system(f'''wget {url} ./''' ) return f'''./{model_name}.ckpt''' __lowerCAmelCase : Optional[int] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', } __lowerCAmelCase : Optional[Any] = { '8': 'resnets.0', '9': 'attentions.0', '10': 'resnets.1', '11': 'attentions.1', '12': 'resnets.2', '13': 'attentions.2', } __lowerCAmelCase : Union[str, Any] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', '8': 'resnets.3', '9': 'attentions.3', '10': 'resnets.4', '11': 'attentions.4', '12': 'resnets.5', '13': 'attentions.5', } __lowerCAmelCase : int = { '0': 'resnets.0', '1': 'resnets.1', '2': 'resnets.2', '4': 'resnets.0', '5': 'resnets.1', '6': 'resnets.2', } __lowerCAmelCase : List[str] = { 'skip': 'conv_skip', 'main.0': 'conv_1', 'main.1': 'group_norm_1', 'main.3': 'conv_2', 'main.4': 'group_norm_2', } __lowerCAmelCase : int = { 'norm': 'group_norm', 'qkv_proj': ['query', 'key', 'value'], 'out_proj': ['proj_attn'], } def a__ ( A_ ): '''simple docstring''' if name.startswith("""skip""" ): return name.replace("""skip""", RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f'''ResConvBlock error with {name}''' ) return name.replace(name[:6], RES_CONV_MAP[name[:6]] ) def a__ ( A_ ): '''simple docstring''' for key, value in ATTN_MAP.items(): if name.startswith(A_ ) and not isinstance(A_, A_ ): return name.replace(A_, A_ ) elif name.startswith(A_ ): return [name.replace(A_, A_ ) for v in value] raise ValueError(f'''Attn error with {name}''' ) def a__ ( A_, A_=13 ): '''simple docstring''' __magic_name__ = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""", """time_proj""" ) __magic_name__ = 0 if string.startswith("""net.3.""" ): depth += 1 __magic_name__ = string[6:] elif string.startswith("""net.""" ): __magic_name__ = string[4:] while string.startswith("""main.7.""" ): depth += 1 __magic_name__ = string[7:] if string.startswith("""main.""" ): __magic_name__ = string[5:] # mid block if string[:2].isdigit(): __magic_name__ = string[:2] __magic_name__ = string[2:] else: __magic_name__ = string[0] __magic_name__ = string[1:] if depth == max_depth: __magic_name__ = MID_NUM_TO_LAYER[layer_num] __magic_name__ = """mid_block""" elif depth > 0 and int(A_ ) < 7: __magic_name__ = DOWN_NUM_TO_LAYER[layer_num] __magic_name__ = f'''down_blocks.{depth}''' elif depth > 0 and int(A_ ) > 7: __magic_name__ = UP_NUM_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - depth - 1}''' elif depth == 0: __magic_name__ = DEPTH_0_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' ) __magic_name__ = string_left[1:] if "resnets" in new_layer: __magic_name__ = convert_resconv_naming(A_ ) elif "attentions" in new_layer: __magic_name__ = convert_attn_naming(A_ ) __magic_name__ = new_string_left if not isinstance(A_, A_ ): __magic_name__ = prefix + """.""" + new_layer + """.""" + string_left else: __magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def a__ ( A_ ): '''simple docstring''' __magic_name__ = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue __magic_name__ = rename(A_ ) # check if we need to transform from Conv => Linear for attention if isinstance(A_, A_ ): __magic_name__ = transform_conv_attns(A_, A_, A_ ) else: __magic_name__ = v return new_state_dict def a__ ( A_, A_, A_ ): '''simple docstring''' if len(A_ ) == 1: if len(v.shape ) == 3: # weight __magic_name__ = v[:, :, 0] else: # bias __magic_name__ = v else: # qkv matrices __magic_name__ = v.shape[0] __magic_name__ = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __magic_name__ = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}''' __magic_name__ = download(A_ ) __magic_name__ = MODELS_MAP[model_name]["""sample_rate"""] __magic_name__ = MODELS_MAP[model_name]["""sample_size"""] __magic_name__ = Object() __magic_name__ = sample_size __magic_name__ = sample_rate __magic_name__ = 0 __magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ ) __magic_name__ = diffusers_model.state_dict() __magic_name__ = DiffusionUncond(A_ ) orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] ) __magic_name__ = orig_model.diffusion_ema.eval() __magic_name__ = orig_model.state_dict() __magic_name__ = rename_orig_weights(A_ ) __magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}''' assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}''' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}''' if key == "time_proj.weight": __magic_name__ = value.squeeze() __magic_name__ = value diffusers_model.load_state_dict(A_ ) __magic_name__ = 100 __magic_name__ = 33 __magic_name__ = IPNDMScheduler(num_train_timesteps=A_ ) __magic_name__ = torch.manual_seed(A_ ) __magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ ) __magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1] __magic_name__ = get_crash_schedule(A_ ) __magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ ) __magic_name__ = torch.manual_seed(33 ) __magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios __magic_name__ = sampling.iplms_sample(A_, A_, A_, {} ) __magic_name__ = generated.clamp(-1, 1 ) __magic_name__ = (generated - audio).abs().sum() __magic_name__ = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""", A_ ) print("""Diff max""", A_ ) assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/''' print(f'''Conversion for {model_name} successful!''' ) if __name__ == "__main__": __lowerCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') 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=None, type=str, required=True, help='Path to the output model.') __lowerCAmelCase : Union[str, Any] = parser.parse_args() main(args)
76
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[Any] = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """sew-d""" def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) __magic_name__ = hidden_size __magic_name__ = feat_extract_norm __magic_name__ = feat_extract_activation __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = conv_bias __magic_name__ = num_conv_pos_embeddings __magic_name__ = num_conv_pos_embedding_groups __magic_name__ = len(self.conv_dim ) __magic_name__ = num_hidden_layers __magic_name__ = intermediate_size __magic_name__ = squeeze_factor __magic_name__ = max_position_embeddings __magic_name__ = position_buckets __magic_name__ = share_att_key __magic_name__ = relative_attention __magic_name__ = norm_rel_ebd __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = hidden_act __magic_name__ = num_attention_heads __magic_name__ = hidden_dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = feat_proj_dropout __magic_name__ = final_dropout __magic_name__ = layer_norm_eps __magic_name__ = feature_layer_norm_eps __magic_name__ = initializer_range __magic_name__ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __magic_name__ = apply_spec_augment __magic_name__ = mask_time_prob __magic_name__ = mask_time_length __magic_name__ = mask_time_min_masks __magic_name__ = mask_feature_prob __magic_name__ = mask_feature_length __magic_name__ = mask_feature_min_masks # ctc loss __magic_name__ = ctc_loss_reduction __magic_name__ = ctc_zero_infinity # sequence classification __magic_name__ = use_weighted_layer_sum __magic_name__ = classifier_proj_size @property def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """lilt""" def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = classifier_dropout __magic_name__ = channel_shrink_ratio __magic_name__ = max_ad_position_embeddings
76
1
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) __lowerCAmelCase : Union[str, Any] = logging.getLogger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : str=None ) -> int: """simple docstring""" __magic_name__ = self.layer[current_layer](UpperCamelCase__ , UpperCamelCase__ , head_mask[current_layer] ) __magic_name__ = layer_outputs[0] return hidden_states @add_start_docstrings( """The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top.""" , _A , ) class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Optional[Any] , UpperCamelCase__ : Dict ) -> Dict: """simple docstring""" super().__init__(UpperCamelCase__ ) __magic_name__ = BertEncoderWithPabee(UpperCamelCase__ ) self.init_weights() __magic_name__ = 0 __magic_name__ = 0 __magic_name__ = 0 __magic_name__ = 0 def _lowercase ( self : Tuple , UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" __magic_name__ = threshold def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = patience def _lowercase ( self : Optional[int] ) -> Dict: """simple docstring""" __magic_name__ = 0 __magic_name__ = 0 def _lowercase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.inference_layers_num / self.inference_instances_num __magic_name__ = ( F'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =''' F''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***''' ) print(UpperCamelCase__ ) @add_start_docstrings_to_model_forward(UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Tuple=False , ) -> List[str]: """simple docstring""" if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __magic_name__ = input_ids.size() elif inputs_embeds is not None: __magic_name__ = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __magic_name__ = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __magic_name__ = torch.ones(UpperCamelCase__ , device=UpperCamelCase__ ) if token_type_ids is None: __magic_name__ = torch.zeros(UpperCamelCase__ , dtype=torch.long , device=UpperCamelCase__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __magic_name__ = self.get_extended_attention_mask(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: __magic_name__ , __magic_name__ , __magic_name__ = encoder_hidden_states.size() __magic_name__ = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: __magic_name__ = torch.ones(UpperCamelCase__ , device=UpperCamelCase__ ) __magic_name__ = self.invert_attention_mask(UpperCamelCase__ ) else: __magic_name__ = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __magic_name__ = self.get_head_mask(UpperCamelCase__ , self.config.num_hidden_layers ) __magic_name__ = self.embeddings( input_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ ) __magic_name__ = embedding_output if self.training: __magic_name__ = [] for i in range(self.config.num_hidden_layers ): __magic_name__ = self.encoder.adaptive_forward( UpperCamelCase__ , current_layer=UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ ) __magic_name__ = self.pooler(UpperCamelCase__ ) __magic_name__ = output_layers[i](output_dropout(UpperCamelCase__ ) ) res.append(UpperCamelCase__ ) elif self.patience == 0: # Use all layers for inference __magic_name__ = self.encoder( UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , ) __magic_name__ = self.pooler(encoder_outputs[0] ) __magic_name__ = [output_layers[self.config.num_hidden_layers - 1](UpperCamelCase__ )] else: __magic_name__ = 0 __magic_name__ = None __magic_name__ = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 __magic_name__ = self.encoder.adaptive_forward( UpperCamelCase__ , current_layer=UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ ) __magic_name__ = self.pooler(UpperCamelCase__ ) __magic_name__ = output_layers[i](UpperCamelCase__ ) if regression: __magic_name__ = logits.detach() if patient_result is not None: __magic_name__ = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: __magic_name__ = 0 else: __magic_name__ = logits.detach().argmax(dim=1 ) if patient_result is not None: __magic_name__ = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(UpperCamelCase__ ) ): patient_counter += 1 else: __magic_name__ = 0 __magic_name__ = logits if patient_counter == self.patience: break __magic_name__ = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( """Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """ , _A , ) class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCamelCase__ : List[str] ) -> Dict: """simple docstring""" super().__init__(UpperCamelCase__ ) __magic_name__ = config.num_labels __magic_name__ = BertModelWithPabee(UpperCamelCase__ ) __magic_name__ = nn.Dropout(config.hidden_dropout_prob ) __magic_name__ = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : int=None , UpperCamelCase__ : str=None , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Any=None , ) -> Dict: """simple docstring""" __magic_name__ = self.bert( input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) __magic_name__ = (logits[-1],) if labels is not None: __magic_name__ = None __magic_name__ = 0 for ix, logits_item in enumerate(UpperCamelCase__ ): if self.num_labels == 1: # We are doing regression __magic_name__ = MSELoss() __magic_name__ = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: __magic_name__ = CrossEntropyLoss() __magic_name__ = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: __magic_name__ = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 __magic_name__ = (total_loss / total_weights,) + outputs return outputs
76
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class UpperCAmelCase_ : '''simple docstring''' a__ = None def _lowercase ( self : Optional[int] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__ = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" ) feat_extract_first.to_json_file(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : str ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : Optional[int] ) -> Tuple: """simple docstring""" __magic_name__ = self.feature_extraction_class() self.assertIsNotNone(UpperCamelCase__ )
76
1
from math import log from scipy.constants import Boltzmann, physical_constants __lowerCAmelCase : int = 300 # TEMPERATURE (unit = K) def a__ ( A_, A_, A_, ): '''simple docstring''' if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
76
from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_A ): '''simple docstring''' a__ = ["""note_seq"""] def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""note_seq"""] ) @classmethod def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" requires_backends(cls , ["""note_seq"""] ) @classmethod def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int: """simple docstring""" requires_backends(cls , ["""note_seq"""] )
76
1
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = DownBlockaD # noqa F405 a__ = """down""" def _lowercase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = ResnetDownsampleBlockaD # noqa F405 a__ = """down""" def _lowercase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" __magic_name__ = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnDownBlockaD # noqa F405 a__ = """down""" def _lowercase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __magic_name__ = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = CrossAttnDownBlockaD # noqa F405 a__ = """down""" def _lowercase ( self : List[Any] ) -> Tuple: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict def _lowercase ( self : List[Any] ) -> Tuple: """simple docstring""" __magic_name__ = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = SimpleCrossAttnDownBlockaD # noqa F405 a__ = """down""" @property def _lowercase ( self : Dict ) -> Any: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=UpperCamelCase__ ) def _lowercase ( self : str ) -> Union[str, Any]: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def _lowercase ( self : Any ) -> List[Any]: """simple docstring""" __magic_name__ = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = SkipDownBlockaD # noqa F405 a__ = """down""" @property def _lowercase ( self : List[Any] ) -> str: """simple docstring""" return super().get_dummy_input(include_skip_sample=UpperCamelCase__ ) def _lowercase ( self : Dict ) -> str: """simple docstring""" __magic_name__ = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnSkipDownBlockaD # noqa F405 a__ = """down""" @property def _lowercase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" return super().get_dummy_input(include_skip_sample=UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = DownEncoderBlockaD # noqa F405 a__ = """down""" @property def _lowercase ( self : Any ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_temb=UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> List[str]: """simple docstring""" __magic_name__ = { """in_channels""": 32, """out_channels""": 32, } __magic_name__ = self.dummy_input return init_dict, inputs_dict def _lowercase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnDownEncoderBlockaD # noqa F405 a__ = """down""" @property def _lowercase ( self : List[str] ) -> str: """simple docstring""" return super().get_dummy_input(include_temb=UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = { """in_channels""": 32, """out_channels""": 32, } __magic_name__ = self.dummy_input return init_dict, inputs_dict def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = UNetMidBlockaD # noqa F405 a__ = """mid""" def _lowercase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = { """in_channels""": 32, """temb_channels""": 128, } __magic_name__ = self.dummy_input return init_dict, inputs_dict def _lowercase ( self : int ) -> Any: """simple docstring""" __magic_name__ = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = UNetMidBlockaDCrossAttn # noqa F405 a__ = """mid""" def _lowercase ( self : Any ) -> Any: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict def _lowercase ( self : Any ) -> List[str]: """simple docstring""" __magic_name__ = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = UNetMidBlockaDSimpleCrossAttn # noqa F405 a__ = """mid""" @property def _lowercase ( self : List[str] ) -> Tuple: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> int: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict def _lowercase ( self : List[str] ) -> Optional[Any]: """simple docstring""" __magic_name__ = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = UpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : int ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) def _lowercase ( self : Tuple ) -> int: """simple docstring""" __magic_name__ = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = ResnetUpsampleBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) def _lowercase ( self : str ) -> Optional[int]: """simple docstring""" __magic_name__ = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = CrossAttnUpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Any ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) def _lowercase ( self : Dict ) -> Any: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = SimpleCrossAttnUpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ , include_encoder_hidden_states=UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common() __magic_name__ = 32 return init_dict, inputs_dict def _lowercase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __magic_name__ = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnUpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Any ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def _lowercase ( self : Dict ) -> str: """simple docstring""" __magic_name__ = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = SkipUpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> Dict: """simple docstring""" __magic_name__ = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnSkipUpBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Any ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __magic_name__ = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = UpDecoderBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : str ) -> List[Any]: """simple docstring""" return super().get_dummy_input(include_temb=UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = {"""in_channels""": 32, """out_channels""": 32} __magic_name__ = self.dummy_input return init_dict, inputs_dict def _lowercase ( self : Optional[int] ) -> Tuple: """simple docstring""" __magic_name__ = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137] super().test_output(UpperCamelCase__ ) class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = AttnUpDecoderBlockaD # noqa F405 a__ = """up""" @property def _lowercase ( self : Tuple ) -> Tuple: """simple docstring""" return super().get_dummy_input(include_temb=UpperCamelCase__ ) def _lowercase ( self : Any ) -> Union[str, Any]: """simple docstring""" __magic_name__ = {"""in_channels""": 32, """out_channels""": 32} __magic_name__ = self.dummy_input return init_dict, inputs_dict def _lowercase ( self : Any ) -> List[str]: """simple docstring""" __magic_name__ = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568] super().test_output(UpperCamelCase__ )
76
def a__ ( A_ ): '''simple docstring''' return " ".join( """""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
76
1
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = None if token is not None: __magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} __magic_name__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __magic_name__ = requests.get(A_, headers=A_ ).json() __magic_name__ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) __magic_name__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(A_ ): __magic_name__ = requests.get(url + f'''&page={i + 2}''', headers=A_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = None if token is not None: __magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} __magic_name__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' __magic_name__ = requests.get(A_, headers=A_ ).json() __magic_name__ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) __magic_name__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(A_ ): __magic_name__ = requests.get(url + f'''&page={i + 2}''', headers=A_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = None if token is not None: __magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} __magic_name__ = requests.get(A_, headers=A_, allow_redirects=A_ ) __magic_name__ = result.headers["""Location"""] __magic_name__ = requests.get(A_, allow_redirects=A_ ) __magic_name__ = os.path.join(A_, f'''{artifact_name}.zip''' ) with open(A_, """wb""" ) as fp: fp.write(response.content ) def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = [] __magic_name__ = [] __magic_name__ = None with zipfile.ZipFile(A_ ) as z: for filename in z.namelist(): if not os.path.isdir(A_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(A_ ) as f: for line in f: __magic_name__ = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs __magic_name__ = line[: line.index(""": """ )] __magic_name__ = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed __magic_name__ = line[len("""FAILED """ ) :] failed_tests.append(A_ ) elif filename == "job_name.txt": __magic_name__ = line if len(A_ ) != len(A_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(A_ )} for `errors` ''' f'''and {len(A_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) __magic_name__ = None if job_name and job_links: __magic_name__ = job_links.get(A_, A_ ) # A list with elements of the form (line of error, error, failed test) __magic_name__ = [x + [y] + [job_link] for x, y in zip(A_, A_ )] return result def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = [] __magic_name__ = [os.path.join(A_, A_ ) for p in os.listdir(A_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(A_, job_links=A_ ) ) return errors def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = Counter() counter.update([x[1] for x in logs] ) __magic_name__ = counter.most_common() __magic_name__ = {} for error, count in counts: if error_filter is None or error not in error_filter: __magic_name__ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} __magic_name__ = dict(sorted(r.items(), key=lambda A_ : item[1]["count"], reverse=A_ ) ) return r def a__ ( A_ ): '''simple docstring''' __magic_name__ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): __magic_name__ = test.split("""/""" )[2] else: __magic_name__ = None return test def a__ ( A_, A_=None ): '''simple docstring''' __magic_name__ = [(x[0], x[1], get_model(x[2] )) for x in logs] __magic_name__ = [x for x in logs if x[2] is not None] __magic_name__ = {x[2] for x in logs} __magic_name__ = {} for test in tests: __magic_name__ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) __magic_name__ = counter.most_common() __magic_name__ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} __magic_name__ = sum(error_counts.values() ) if n_errors > 0: __magic_name__ = {"""count""": n_errors, """errors""": error_counts} __magic_name__ = dict(sorted(r.items(), key=lambda A_ : item[1]["count"], reverse=A_ ) ) return r def a__ ( A_ ): '''simple docstring''' __magic_name__ = """| no. | error | status |""" __magic_name__ = """|-:|:-|:-|""" __magic_name__ = [header, sep] for error in reduced_by_error: __magic_name__ = reduced_by_error[error]["""count"""] __magic_name__ = f'''| {count} | {error[:100]} | |''' lines.append(A_ ) return "\n".join(A_ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = """| model | no. of errors | major error | count |""" __magic_name__ = """|-:|-:|-:|-:|""" __magic_name__ = [header, sep] for model in reduced_by_model: __magic_name__ = reduced_by_model[model]["""count"""] __magic_name__ , __magic_name__ = list(reduced_by_model[model]["""errors"""].items() )[0] __magic_name__ = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(A_ ) return "\n".join(A_ ) if __name__ == "__main__": __lowerCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') __lowerCAmelCase : Dict = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) __lowerCAmelCase : List[str] = get_job_links(args.workflow_run_id, token=args.token) __lowerCAmelCase : Dict = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: __lowerCAmelCase : Optional[int] = k.find(' / ') __lowerCAmelCase : List[str] = k[index + len(' / ') :] __lowerCAmelCase : Dict = v with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) __lowerCAmelCase : Tuple = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) __lowerCAmelCase : List[str] = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error __lowerCAmelCase : str = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors __lowerCAmelCase : str = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) __lowerCAmelCase : Optional[Any] = reduce_by_error(errors) __lowerCAmelCase : Optional[int] = reduce_by_model(errors) __lowerCAmelCase : Dict = make_github_table(reduced_by_error) __lowerCAmelCase : Optional[int] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa) with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa)
76
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = FunnelTokenizer a__ = FunnelTokenizerFast a__ = True a__ = True def _lowercase ( self : List[Any] ) -> str: """simple docstring""" super().setUp() __magic_name__ = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]: """simple docstring""" __magic_name__ = """UNwant\u00E9d,running""" __magic_name__ = """unwanted, running""" return input_text, output_text def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __magic_name__ = self.tokenizer_class(self.vocab_file ) __magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def _lowercase ( self : str ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: __magic_name__ = tokenizer("""UNwant\u00E9d,running""" ) __magic_name__ = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) __magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
76
1
__lowerCAmelCase : int = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' __lowerCAmelCase : Optional[int] = [{'type': 'code', 'content': INSTALL_CONTENT}] __lowerCAmelCase : List[str] = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
76
from collections import deque from .hash_table import HashTable class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(UpperCamelCase__ ) __magic_name__ = self.values[key] def _lowercase ( self : List[str] ) -> int: """simple docstring""" return ( sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values ) / self.size_table * self.charge_factor ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str: """simple docstring""" if not ( len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0 ): return key return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
76
1
from __future__ import annotations import math def a__ ( A_ ): '''simple docstring''' if num <= 0: __magic_name__ = f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(A_ ) __magic_name__ = [True] * (num + 1) __magic_name__ = [] __magic_name__ = 2 __magic_name__ = int(math.sqrt(A_ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(A_ ) # Set multiples of start be False for i in range(start * start, num + 1, A_ ): if sieve[i] is True: __magic_name__ = False start += 1 for j in range(end + 1, num + 1 ): if sieve[j] is True: prime.append(A_ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
76
# 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 json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def a__ ( A_ ): '''simple docstring''' __magic_name__ = botoa.client("""iam""" ) __magic_name__ = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) ) __magic_name__ = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), ) except iam_client.exceptions.EntityAlreadyExistsException: print(f'''role {role_name} already exists. Using existing one''' ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def a__ ( ): '''simple docstring''' __magic_name__ = _ask_options( """How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, ) __magic_name__ = None if credentials_configuration == 0: __magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" ) __magic_name__ = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __magic_name__ = _ask_field("""AWS Access Key ID: """ ) __magic_name__ = aws_access_key_id __magic_name__ = _ask_field("""AWS Secret Access Key: """ ) __magic_name__ = aws_secret_access_key __magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" ) __magic_name__ = aws_region __magic_name__ = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, ) if role_management == 0: __magic_name__ = _ask_field("""Enter your IAM role name: """ ) else: __magic_name__ = """accelerate_sagemaker_execution_role""" print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __magic_name__ = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_custom_docker_image: __magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() ) __magic_name__ = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_sagemaker_inputs_enabled: __magic_name__ = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), ) __magic_name__ = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = None if is_sagemaker_metrics_enabled: __magic_name__ = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), ) __magic_name__ = _ask_options( """What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, ) __magic_name__ = {} __magic_name__ = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) if use_dynamo: __magic_name__ = """dynamo_""" __magic_name__ = _ask_options( """Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) __magic_name__ = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) if use_custom_options: __magic_name__ = _ask_options( """Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", ) __magic_name__ = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", ) __magic_name__ = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __magic_name__ = _ask_options( A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" ) __magic_name__ = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __magic_name__ = _ask_field( """How many machines do you want use? [1]: """, A_, default=1, ) __magic_name__ = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
76
1
from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_A ): '''simple docstring''' a__ = ["""keras_nlp"""] def __init__( self : str , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : str ) -> List[Any]: """simple docstring""" requires_backends(self , ["""keras_nlp"""] )
76
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 __lowerCAmelCase : Dict = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD __magic_name__ = do_convert_rgb def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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, width). Got {size.keys()}''' ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __magic_name__ = 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.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: __magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
1
import math import tensorflow as tf from packaging import version def a__ ( A_ ): '''simple docstring''' __magic_name__ = tf.convert_to_tensor(A_ ) __magic_name__ = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ), x.dtype ) )) return x * cdf def a__ ( A_ ): '''simple docstring''' __magic_name__ = tf.convert_to_tensor(A_ ) __magic_name__ = tf.cast(math.pi, x.dtype ) __magic_name__ = tf.cast(0.044715, x.dtype ) __magic_name__ = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(A_, 3 )) )) return x * cdf def a__ ( A_ ): '''simple docstring''' __magic_name__ = tf.convert_to_tensor(A_ ) return x * tf.tanh(tf.math.softplus(A_ ) ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = tf.convert_to_tensor(A_ ) __magic_name__ = tf.cast(0.044715, x.dtype ) __magic_name__ = tf.cast(0.7978845608, x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def a__ ( A_ ): '''simple docstring''' __magic_name__ = tf.convert_to_tensor(A_ ) __magic_name__ = tf.cast(1.702, x.dtype ) return x * tf.math.sigmoid(coeff * x ) def a__ ( A_ ): '''simple docstring''' return tf.clip_by_value(_gelu(A_ ), -10, 10 ) def a__ ( A_, A_=-1 ): '''simple docstring''' __magic_name__ , __magic_name__ = tf.split(A_, 2, axis=A_ ) return a * tf.math.sigmoid(A_ ) if version.parse(tf.version.VERSION) >= version.parse('2.4'): def a__ ( A_ ): '''simple docstring''' return tf.keras.activations.gelu(A_, approximate=A_ ) __lowerCAmelCase : List[str] = tf.keras.activations.gelu __lowerCAmelCase : str = approximate_gelu_wrap else: __lowerCAmelCase : Dict = _gelu __lowerCAmelCase : List[Any] = _gelu_new __lowerCAmelCase : Optional[int] = { 'gelu': gelu, 'gelu_10': gelu_aa, 'gelu_fast': gelu_fast, 'gelu_new': gelu_new, 'glu': glu, 'mish': mish, 'quick_gelu': quick_gelu, 'relu': tf.keras.activations.relu, 'sigmoid': tf.keras.activations.sigmoid, 'silu': tf.keras.activations.swish, 'swish': tf.keras.activations.swish, 'tanh': tf.keras.activations.tanh, } def a__ ( A_ ): '''simple docstring''' if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
76
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Any ) -> Any: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Tuple ) -> Any: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , ) def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple: """simple docstring""" __magic_name__ = NystromformerModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str: """simple docstring""" __magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a__ = False a__ = False def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = NystromformerModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : str ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def _lowercase ( self : str ) -> Tuple: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) ) @slow def _lowercase ( self : int ) -> str: """simple docstring""" __magic_name__ = """the [MASK] of Belgium is Brussels""" __magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" ) with torch.no_grad(): __magic_name__ = model(encoding.input_ids ).logits __magic_name__ = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
76
1
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : Any = logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] = {'vocab_file': 'vocab.txt'} __lowerCAmelCase : Optional[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } __lowerCAmelCase : List[str] = { 'openbmb/cpm-ant-10b': 1024, } def a__ ( A_ ): '''simple docstring''' __magic_name__ = collections.OrderedDict() with open(A_, """r""", encoding="""utf-8""" ) as reader: __magic_name__ = reader.readlines() for index, token in enumerate(A_ ): __magic_name__ = token.rstrip("""\n""" ) __magic_name__ = index return vocab class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : int=200 ) -> Tuple: """simple docstring""" __magic_name__ = vocab __magic_name__ = unk_token __magic_name__ = max_input_chars_per_word def _lowercase ( self : str , UpperCamelCase__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = list(UpperCamelCase__ ) if len(UpperCamelCase__ ) > self.max_input_chars_per_word: return [self.unk_token] __magic_name__ = 0 __magic_name__ = [] while start < len(UpperCamelCase__ ): __magic_name__ = len(UpperCamelCase__ ) __magic_name__ = None while start < end: __magic_name__ = """""".join(chars[start:end] ) if substr in self.vocab: __magic_name__ = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(UpperCamelCase__ ) __magic_name__ = end return sub_tokens class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = ["""input_ids""", """attention_mask"""] a__ = False def __init__( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any]="<d>" , UpperCamelCase__ : int="</d>" , UpperCamelCase__ : int="<s>" , UpperCamelCase__ : Dict="</s>" , UpperCamelCase__ : List[str]="<pad>" , UpperCamelCase__ : Any="<unk>" , UpperCamelCase__ : Optional[int]="</n>" , UpperCamelCase__ : Union[str, Any]="</_>" , UpperCamelCase__ : Optional[Any]="left" , **UpperCamelCase__ : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""jieba"""] ) super().__init__( bod_token=UpperCamelCase__ , eod_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , line_token=UpperCamelCase__ , space_token=UpperCamelCase__ , padding_side=UpperCamelCase__ , **UpperCamelCase__ , ) __magic_name__ = bod_token __magic_name__ = eod_token __magic_name__ = load_vocab(UpperCamelCase__ ) __magic_name__ = self.encoder[space_token] __magic_name__ = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __magic_name__ = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase__ : x[1] ) ) __magic_name__ = {v: k for k, v in self.encoder.items()} __magic_name__ = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def _lowercase ( self : List[Any] ) -> int: """simple docstring""" return self.encoder[self.bod_token] @property def _lowercase ( self : Tuple ) -> int: """simple docstring""" return self.encoder[self.eod_token] @property def _lowercase ( self : Dict ) -> int: """simple docstring""" return self.encoder["\n"] @property def _lowercase ( self : Any ) -> int: """simple docstring""" return len(self.encoder ) def _lowercase ( self : Tuple ) -> Tuple: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def _lowercase ( self : Any , UpperCamelCase__ : Any ) -> List[str]: """simple docstring""" __magic_name__ = [] for x in jieba.cut(UpperCamelCase__ , cut_all=UpperCamelCase__ ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(UpperCamelCase__ ) ) return output_tokens def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = [i for i in token_ids if i >= 0] __magic_name__ = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" return token in self.encoder def _lowercase ( self : List[Any] , UpperCamelCase__ : List[str] ) -> str: """simple docstring""" return "".join(UpperCamelCase__ ) def _lowercase ( self : Dict , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" return self.encoder.get(UpperCamelCase__ , self.encoder.get(self.unk_token ) ) def _lowercase ( self : int , UpperCamelCase__ : Optional[Any] ) -> Dict: """simple docstring""" return self.decoder.get(UpperCamelCase__ , self.unk_token ) def _lowercase ( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if os.path.isdir(UpperCamelCase__ ): __magic_name__ = os.path.join( UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) else: __magic_name__ = (filename_prefix + """-""" if filename_prefix else """""") + save_directory __magic_name__ = 0 if " " in self.encoder: __magic_name__ = self.encoder[""" """] del self.encoder[" "] if "\n" in self.encoder: __magic_name__ = self.encoder["""\n"""] del self.encoder["\n"] __magic_name__ = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase__ : x[1] ) ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' """ Please check that the vocabulary is not corrupted!""" ) __magic_name__ = token_index writer.write(token + """\n""" ) index += 1 return (vocab_file,) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : List[int] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def _lowercase ( self : List[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = False ) -> List[int]: """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 not None: return [1] + ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) return [1] + ([0] * len(UpperCamelCase__ ))
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Union[str, Any] = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """cvt""" def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = num_channels __magic_name__ = patch_sizes __magic_name__ = patch_stride __magic_name__ = patch_padding __magic_name__ = embed_dim __magic_name__ = num_heads __magic_name__ = depth __magic_name__ = mlp_ratio __magic_name__ = attention_drop_rate __magic_name__ = drop_rate __magic_name__ = drop_path_rate __magic_name__ = qkv_bias __magic_name__ = cls_token __magic_name__ = qkv_projection_method __magic_name__ = kernel_qkv __magic_name__ = padding_kv __magic_name__ = stride_kv __magic_name__ = padding_q __magic_name__ = stride_q __magic_name__ = initializer_range __magic_name__ = layer_norm_eps
76
1
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __lowerCAmelCase : Tuple = 2 class UpperCAmelCase_ : '''simple docstring''' def __init__( self : int , *, # begin keyword-only arguments UpperCamelCase__ : Union[str, Any]="<s>" , UpperCamelCase__ : Tuple="<pad>" , UpperCamelCase__ : List[str]="</s>" , UpperCamelCase__ : int="<unk>" , UpperCamelCase__ : int=None , ) -> Any: """simple docstring""" __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = bos, unk, pad, eos __magic_name__ = [] __magic_name__ = [] __magic_name__ = {} __magic_name__ = self.add_symbol(UpperCamelCase__ ) __magic_name__ = self.add_symbol(UpperCamelCase__ ) __magic_name__ = self.add_symbol(UpperCamelCase__ ) __magic_name__ = self.add_symbol(UpperCamelCase__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(UpperCamelCase__ ) __magic_name__ = len(self.symbols ) def __eq__( self : Dict , UpperCamelCase__ : Union[str, Any] ) -> Optional[int]: """simple docstring""" return self.indices == other.indices def __getitem__( self : Dict , UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : Optional[Any] ) -> List[Any]: """simple docstring""" return len(self.symbols ) def __contains__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]: """simple docstring""" return sym in self.indices @classmethod def _lowercase ( cls : str , UpperCamelCase__ : Any ) -> Union[str, Any]: """simple docstring""" __magic_name__ = cls() d.add_from_file(UpperCamelCase__ ) return d def _lowercase ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : Any=False ) -> Union[str, Any]: """simple docstring""" if word in self.indices and not overwrite: __magic_name__ = self.indices[word] __magic_name__ = self.count[idx] + n return idx else: __magic_name__ = len(self.symbols ) __magic_name__ = idx self.symbols.append(UpperCamelCase__ ) self.count.append(UpperCamelCase__ ) return idx def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : int ) -> List[str]: """simple docstring""" return 0 def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> List[str]: """simple docstring""" 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("""Incorrect encoding detected in {}, please rebuild the dataset""".format(UpperCamelCase__ ) ) return __magic_name__ = f.readlines() __magic_name__ = self._load_meta(UpperCamelCase__ ) for line in lines[indices_start_line:]: try: __magic_name__ , __magic_name__ = line.rstrip().rsplit(""" """ , 1 ) if field == "#fairseq:overwrite": __magic_name__ = True __magic_name__ , __magic_name__ = line.rsplit(""" """ , 1 ) else: __magic_name__ = False __magic_name__ = int(UpperCamelCase__ ) __magic_name__ = line if word in self and not overwrite: raise RuntimeError( """Duplicate word found when loading Dictionary: '{}'. """ """Duplicate words can overwrite earlier ones by adding the """ """#fairseq:overwrite flag at the end of the corresponding row """ """in the dictionary file. If using the Camembert model, please """ """download an updated copy of the model file.""".format(UpperCamelCase__ ) ) self.add_symbol(UpperCamelCase__ , n=UpperCamelCase__ , overwrite=UpperCamelCase__ ) except ValueError: raise ValueError("""Incorrect dictionary format, expected '<token> <cnt> [flags]'""" ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = dict((re.sub(R"""@@$""", """""", A_ ), v) if k.endswith("""@@""" ) else (re.sub(R"""$""", """</w>""", A_ ), v) for k, v in d.items() ) __magic_name__ = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[f'''{k}</w>'''] __magic_name__ = d[k] # restore return da def a__ ( A_, A_ ): '''simple docstring''' if not os.path.exists(A_ ): raise ValueError(f'''path {biogpt_checkpoint_path} does not exist!''' ) os.makedirs(A_, exist_ok=A_ ) print(f'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models __magic_name__ = os.path.join(A_, """checkpoint.pt""" ) if not os.path.isfile(A_ ): raise ValueError(f'''path to the file {checkpoint_file} does not exist!''' ) __magic_name__ = torch.load(A_, map_location="""cpu""" ) __magic_name__ = chkpt["""cfg"""]["""model"""] # dicts __magic_name__ = os.path.join(A_, """dict.txt""" ) if not os.path.isfile(A_ ): raise ValueError(f'''path to the file {dict_file} does not exist!''' ) __magic_name__ = Dictionary.load(A_ ) __magic_name__ = rewrite_dict_keys(src_dict.indices ) __magic_name__ = len(A_ ) __magic_name__ = os.path.join(A_, VOCAB_FILES_NAMES["""vocab_file"""] ) print(f'''Generating {src_vocab_file} of {src_vocab_size} records''' ) with open(A_, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(A_, ensure_ascii=A_, indent=A_ ) ) # merges_file (bpecodes) __magic_name__ = os.path.join(A_, """bpecodes""" ) if not os.path.isfile(A_ ): raise ValueError(f'''path to the file {bpecodes_file} does not exist!''' ) __magic_name__ = os.path.join(A_, VOCAB_FILES_NAMES["""merges_file"""] ) shutil.copyfile(A_, A_ ) # model config __magic_name__ = os.path.join(A_, """config.json""" ) __magic_name__ = { """activation_dropout""": args["""activation_dropout"""], """architectures""": ["""BioGptForCausalLM"""], """attention_probs_dropout_prob""": args["""attention_dropout"""], """bos_token_id""": 0, """eos_token_id""": 2, """hidden_act""": args["""activation_fn"""], """hidden_dropout_prob""": args["""dropout"""], """hidden_size""": args["""decoder_embed_dim"""], """initializer_range""": 0.02, """intermediate_size""": args["""decoder_ffn_embed_dim"""], """layer_norm_eps""": 1e-12, """layerdrop""": args["""decoder_layerdrop"""], """max_position_embeddings""": args["""max_target_positions"""], """model_type""": """biogpt""", """num_attention_heads""": args["""decoder_attention_heads"""], """num_hidden_layers""": args["""decoder_layers"""], """pad_token_id""": 1, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_decoder_input_output_embed"""], """vocab_size""": src_vocab_size, } # good hparam defaults to start with print(f'''Generating {biogpt_model_config_file}''' ) with open(A_, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(A_, ensure_ascii=A_, indent=A_ ) ) # tokenizer config __magic_name__ = os.path.join(A_, A_ ) __magic_name__ = { """bos_token""": """<s>""", """eos_token""": """</s>""", """model_max_length""": 1024, """pad_token""": """<pad>""", """special_tokens_map_file""": None, """tokenizer_class""": """BioGptTokenizer""", """unk_token""": """<unk>""", } print(f'''Generating {biogpt_tokenizer_config_file}''' ) with open(A_, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(A_, ensure_ascii=A_, indent=A_ ) ) # model __magic_name__ = chkpt["""model"""] # remove unneeded keys __magic_name__ = [ """decoder.version""", ] for k in ignore_keys: model_state_dict.pop(A_, A_ ) __magic_name__ = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith("""output_projection.weight""" ): __magic_name__ = model_state_dict.pop(A_ ) else: __magic_name__ = model_state_dict.pop(A_ ) __magic_name__ = BioGptConfig.from_pretrained(A_ ) __magic_name__ = BioGptForCausalLM(A_ ) # check that it loads ok model_new.load_state_dict(A_ ) # save __magic_name__ = os.path.join(A_, A_ ) print(f'''Generating {pytorch_weights_dump_path}''' ) torch.save(A_, A_ ) print("""Conversion is done!""" ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--biogpt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __lowerCAmelCase : List[str] = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
76
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase : List[str] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[Any] = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys __lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase : List[Any] = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : str = [ 'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Swinv2ForImageClassification', 'Swinv2ForMaskedImageModeling', 'Swinv2Model', 'Swinv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys __lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""projector.weight"""] __magic_name__ = downstream_dict["""projector.bias"""] __magic_name__ = downstream_dict["""model.post_net.linear.weight"""] __magic_name__ = downstream_dict["""model.post_net.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""model.linear.weight"""] __magic_name__ = downstream_dict["""model.linear.bias"""] return model def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ ) __magic_name__ = downstream_dict["""connector.weight"""] __magic_name__ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __magic_name__ = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] __magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] __magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] __magic_name__ = downstream_dict["""objective.W"""] return model @torch.no_grad() def a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = torch.load(A_, map_location="""cpu""" ) __magic_name__ = checkpoint["""Downstream"""] __magic_name__ = WavaVecaConfig.from_pretrained(A_ ) __magic_name__ = WavaVecaFeatureExtractor.from_pretrained( A_, return_attention_mask=A_, do_normalize=A_ ) __magic_name__ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): __magic_name__ = convert_classification(A_, A_, A_ ) elif arch.endswith("""ForAudioFrameClassification""" ): __magic_name__ = convert_diarization(A_, A_, A_ ) elif arch.endswith("""ForXVector""" ): __magic_name__ = convert_xvector(A_, A_, A_ ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: __magic_name__ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(A_ ) hf_model.save_pretrained(A_ ) if __name__ == "__main__": __lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __lowerCAmelCase : str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
76
1
def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = len(A_ ) __magic_name__ = len(A_ ) __magic_name__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] __magic_name__ = True for i in range(A_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: __magic_name__ = True if a[i].islower(): __magic_name__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
76
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a__ ( A_, A_ ): '''simple docstring''' assert isinstance(A_, A_ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read() _check_text_dataset(A_, A_ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""", [str, list] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if issubclass(A_, A_ ): __magic_name__ = text_path elif issubclass(A_, A_ ): __magic_name__ = [text_path] __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_dataset(A_, A_ ) def a__ ( A_, A_, A_=("train",) ): '''simple docstring''' assert isinstance(A_, A_ ) for split in splits: __magic_name__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""", [False, True] ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize( """features""", [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ], ) def a__ ( A_, A_, A_ ): '''simple docstring''' __magic_name__ = tmp_path / """cache""" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __magic_name__ = {"""text""": """string"""} __magic_name__ = features.copy() if features else default_expected_features __magic_name__ = ( Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None ) __magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_ ) @pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] ) def a__ ( A_, A_, A_ ): '''simple docstring''' if split: __magic_name__ = {split: text_path} else: __magic_name__ = """train""" __magic_name__ = {"""train""": text_path, """test""": text_path} __magic_name__ = tmp_path / """cache""" __magic_name__ = {"""text""": """string"""} __magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read() _check_text_datasetdict(A_, A_, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
76
1
import collections import importlib.util import os import re from pathlib import Path __lowerCAmelCase : int = 'src/transformers' # Matches is_xxx_available() __lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} __lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", __lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], __lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo __lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: __lowerCAmelCase : int = re.compile(R'^\s*try:') # Catches a line with else: __lowerCAmelCase : Tuple = re.compile(R'^\s*else:') def a__ ( A_ ): '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None __magic_name__ = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def a__ ( A_ ): '''simple docstring''' with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f: __magic_name__ = f.readlines() __magic_name__ = 0 while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure __magic_name__ = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: __magic_name__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): __magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0] __magic_name__ = re.findall("""\[([^\]]+)\]""", A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue __magic_name__ = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: __magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): __magic_name__ = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: __magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: __magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 __magic_name__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __magic_name__ = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 __magic_name__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def a__ ( A_, A_ ): '''simple docstring''' def find_duplicates(A_ ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __magic_name__ = [] for key in import_dict_objects.keys(): __magic_name__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) __magic_name__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __magic_name__ = """base imports""" if key == """none""" else f'''{key} backend''' errors.append(f'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def a__ ( ): '''simple docstring''' __magic_name__ = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: __magic_name__ = os.path.join(A_, """__init__.py""" ) __magic_name__ = parse_init(A_ ) if objects is not None: __magic_name__ = analyze_results(*A_ ) if len(A_ ) > 0: __magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("""\n""".join(A_ ) ) if len(A_ ) > 0: raise ValueError("""\n\n""".join(A_ ) ) def a__ ( ): '''simple docstring''' __magic_name__ = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0: continue __magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) ) __magic_name__ = short_path.replace(os.path.sep, """.""" ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue __magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) ) __magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(A_ ) return submodules __lowerCAmelCase : Dict = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def a__ ( ): '''simple docstring''' __magic_name__ = importlib.util.spec_from_file_location( """transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) __magic_name__ = spec.loader.load_module() __magic_name__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: __magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registered in the main init of Transformers:\n""" f'''{list_of_modules}\n''' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
76
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, 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, logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""pixel_values"""] def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = size if size is not None else {"""shortest_edge""": 256} __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: """simple docstring""" __magic_name__ = 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()}''' ) __magic_name__ = 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 _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" __magic_name__ = get_size_dict(UpperCamelCase__ ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray: """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray: """simple docstring""" return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict: """simple docstring""" __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(UpperCamelCase__ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = 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. __magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __magic_name__ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
76
1
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( _A , unittest.TestCase ): '''simple docstring''' a__ = FunnelTokenizer a__ = FunnelTokenizerFast a__ = True a__ = True def _lowercase ( self : List[Any] ) -> str: """simple docstring""" super().setUp() __magic_name__ = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]: """simple docstring""" __magic_name__ = """UNwant\u00E9d,running""" __magic_name__ = """unwanted, running""" return input_text, output_text def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __magic_name__ = self.tokenizer_class(self.vocab_file ) __magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def _lowercase ( self : str ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: __magic_name__ = tokenizer("""UNwant\u00E9d,running""" ) __magic_name__ = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) __magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
76
import math def a__ ( A_, A_ = 0, A_ = 0 ): '''simple docstring''' __magic_name__ = end or len(A_ ) for i in range(A_, A_ ): __magic_name__ = i __magic_name__ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __magic_name__ = array[temp_index - 1] temp_index -= 1 __magic_name__ = temp_index_value return array def a__ ( A_, A_, A_ ): # Max Heap '''simple docstring''' __magic_name__ = index __magic_name__ = 2 * index + 1 # Left Node __magic_name__ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __magic_name__ = left_index if right_index < heap_size and array[largest] < array[right_index]: __magic_name__ = right_index if largest != index: __magic_name__ , __magic_name__ = array[largest], array[index] heapify(A_, A_, A_ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = len(A_ ) for i in range(n // 2, -1, -1 ): heapify(A_, A_, A_ ) for i in range(n - 1, 0, -1 ): __magic_name__ , __magic_name__ = array[0], array[i] heapify(A_, 0, A_ ) return array def a__ ( A_, A_, A_, A_ ): '''simple docstring''' 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 a__ ( A_, A_, A_, A_ ): '''simple docstring''' __magic_name__ = low __magic_name__ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __magic_name__ , __magic_name__ = array[j], array[i] i += 1 def a__ ( A_ ): '''simple docstring''' if len(A_ ) == 0: return array __magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) ) __magic_name__ = 16 return intro_sort(A_, 0, len(A_ ), A_, A_ ) def a__ ( A_, A_, A_, A_, A_ ): '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(A_ ) max_depth -= 1 __magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 ) __magic_name__ = partition(A_, A_, A_, A_ ) intro_sort(A_, A_, A_, A_, A_ ) __magic_name__ = p return insertion_sort(A_, A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip() __lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')] print(sort(unsorted))
76
1
from functools import lru_cache def a__ ( A_ ): '''simple docstring''' __magic_name__ = 2 __magic_name__ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(A_ ) if n > 1: factors.add(A_ ) return factors @lru_cache def a__ ( A_ ): '''simple docstring''' return len(unique_prime_factors(A_ ) ) def a__ ( A_ ): '''simple docstring''' return len(set(A_ ) ) in (0, 1) def a__ ( A_ ): '''simple docstring''' __magic_name__ = 2 while True: # Increment each value of a generated range __magic_name__ = [base + i for i in range(A_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. __magic_name__ = [upf_len(A_ ) for x in group] checker.append(A_ ) # If all numbers in the list are equal, return the group variable. if equality(A_ ): return group # Increment our base variable by 1 base += 1 def a__ ( A_ = 4 ): '''simple docstring''' __magic_name__ = run(A_ ) return results[0] if len(A_ ) else None if __name__ == "__main__": print(solution())
76
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) __magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ ) if matches: __magic_name__ = float(matches[1] ) __magic_name__ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __magic_name__ = 1001 __magic_name__ = """imagenet-1k-id2label.json""" __magic_name__ = """huggingface/label-files""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()} __magic_name__ = """background""" __magic_name__ = idalabel __magic_name__ = {v: k for k, v in idalabel.items()} return config def a__ ( ): '''simple docstring''' __magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" __magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ) return im @torch.no_grad() def a__ ( A_, A_, A_, A_=False ): '''simple docstring''' __magic_name__ = get_mobilenet_va_config(A_ ) # Load 🤗 model __magic_name__ = MobileNetVaForImageClassification(A_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(A_, A_, A_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __magic_name__ = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, ) __magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" ) __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __magic_name__ = None if expected_logits is not None: assert torch.allclose(logits[0, :3], A_, atol=1e-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if push_to_hub: print("""Pushing to the hub...""" ) __magic_name__ = """google/""" + model_name image_processor.push_to_hub(A_ ) model.push_to_hub(A_ ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : str = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
76
1
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) __magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ ) if matches: __magic_name__ = float(matches[1] ) __magic_name__ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __magic_name__ = 1001 __magic_name__ = """imagenet-1k-id2label.json""" __magic_name__ = """huggingface/label-files""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()} __magic_name__ = """background""" __magic_name__ = idalabel __magic_name__ = {v: k for k, v in idalabel.items()} return config def a__ ( ): '''simple docstring''' __magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" __magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ) return im @torch.no_grad() def a__ ( A_, A_, A_, A_=False ): '''simple docstring''' __magic_name__ = get_mobilenet_va_config(A_ ) # Load 🤗 model __magic_name__ = MobileNetVaForImageClassification(A_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(A_, A_, A_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __magic_name__ = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, ) __magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" ) __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __magic_name__ = None if expected_logits is not None: assert torch.allclose(logits[0, :3], A_, atol=1e-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if push_to_hub: print("""Pushing to the hub...""" ) __magic_name__ = """google/""" + model_name image_processor.push_to_hub(A_ ) model.push_to_hub(A_ ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : str = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
76
import collections import importlib.util import os import re from pathlib import Path __lowerCAmelCase : int = 'src/transformers' # Matches is_xxx_available() __lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} __lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") __lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", __lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], __lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo __lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: __lowerCAmelCase : int = re.compile(R'^\s*try:') # Catches a line with else: __lowerCAmelCase : Tuple = re.compile(R'^\s*else:') def a__ ( A_ ): '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None __magic_name__ = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def a__ ( A_ ): '''simple docstring''' with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f: __magic_name__ = f.readlines() __magic_name__ = 0 while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure __magic_name__ = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: __magic_name__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): __magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0] __magic_name__ = re.findall("""\[([^\]]+)\]""", A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue __magic_name__ = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: __magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): __magic_name__ = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: __magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: __magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ ) __magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 __magic_name__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __magic_name__ = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 __magic_name__ = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. __magic_name__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __magic_name__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __magic_name__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): __magic_name__ = lines[line_index] __magic_name__ = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 __magic_name__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def a__ ( A_, A_ ): '''simple docstring''' def find_duplicates(A_ ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __magic_name__ = [] for key in import_dict_objects.keys(): __magic_name__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) __magic_name__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __magic_name__ = """base imports""" if key == """none""" else f'''{key} backend''' errors.append(f'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def a__ ( ): '''simple docstring''' __magic_name__ = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: __magic_name__ = os.path.join(A_, """__init__.py""" ) __magic_name__ = parse_init(A_ ) if objects is not None: __magic_name__ = analyze_results(*A_ ) if len(A_ ) > 0: __magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("""\n""".join(A_ ) ) if len(A_ ) > 0: raise ValueError("""\n\n""".join(A_ ) ) def a__ ( ): '''simple docstring''' __magic_name__ = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0: continue __magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) ) __magic_name__ = short_path.replace(os.path.sep, """.""" ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue __magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) ) __magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(A_ ) return submodules __lowerCAmelCase : Dict = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def a__ ( ): '''simple docstring''' __magic_name__ = importlib.util.spec_from_file_location( """transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) __magic_name__ = spec.loader.load_module() __magic_name__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: __magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registered in the main init of Transformers:\n""" f'''{list_of_modules}\n''' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
76
1
import os __lowerCAmelCase : Dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def a__ ( A_ ): '''simple docstring''' __magic_name__ = 0 __magic_name__ = 0 while index < len(A_ ) - 1: __magic_name__ = SYMBOLS[numerals[index]] __magic_name__ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def a__ ( A_ ): '''simple docstring''' __magic_name__ = """""" __magic_name__ = num // 1000 numerals += m_count * "M" num %= 1000 __magic_name__ = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 __magic_name__ = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def a__ ( A_ = "/p089_roman.txt" ): '''simple docstring''' __magic_name__ = 0 with open(os.path.dirname(A_ ) + roman_numerals_filename ) as filea: __magic_name__ = filea.readlines() for line in lines: __magic_name__ = line.strip() __magic_name__ = parse_roman_numerals(A_ ) __magic_name__ = generate_roman_numerals(A_ ) savings += len(A_ ) - len(A_ ) return savings if __name__ == "__main__": print(F'''{solution() = }''')
76
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[Any] = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """sew-d""" def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict: """simple docstring""" super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) __magic_name__ = hidden_size __magic_name__ = feat_extract_norm __magic_name__ = feat_extract_activation __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = conv_bias __magic_name__ = num_conv_pos_embeddings __magic_name__ = num_conv_pos_embedding_groups __magic_name__ = len(self.conv_dim ) __magic_name__ = num_hidden_layers __magic_name__ = intermediate_size __magic_name__ = squeeze_factor __magic_name__ = max_position_embeddings __magic_name__ = position_buckets __magic_name__ = share_att_key __magic_name__ = relative_attention __magic_name__ = norm_rel_ebd __magic_name__ = list(UpperCamelCase__ ) __magic_name__ = hidden_act __magic_name__ = num_attention_heads __magic_name__ = hidden_dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = feat_proj_dropout __magic_name__ = final_dropout __magic_name__ = layer_norm_eps __magic_name__ = feature_layer_norm_eps __magic_name__ = initializer_range __magic_name__ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __magic_name__ = apply_spec_augment __magic_name__ = mask_time_prob __magic_name__ = mask_time_length __magic_name__ = mask_time_min_masks __magic_name__ = mask_feature_prob __magic_name__ = mask_feature_length __magic_name__ = mask_feature_min_masks # ctc loss __magic_name__ = ctc_loss_reduction __magic_name__ = ctc_zero_infinity # sequence classification __magic_name__ = use_weighted_layer_sum __magic_name__ = classifier_proj_size @property def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
76
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = (DPMSolverSinglestepScheduler,) a__ = (("""num_inference_steps""", 25),) def _lowercase ( self : Optional[Any] , **UpperCamelCase__ : int ) -> Any: """simple docstring""" __magic_name__ = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, """prediction_type""": """epsilon""", """thresholding""": False, """sample_max_value""": 1.0, """algorithm_type""": """dpmsolver++""", """solver_type""": """midpoint""", """lambda_min_clipped""": -float("""inf""" ), """variance_type""": None, } config.update(**UpperCamelCase__ ) return config def _lowercase ( self : List[Any] , UpperCamelCase__ : Any=0 , **UpperCamelCase__ : List[Any] ) -> str: """simple docstring""" __magic_name__ = dict(self.forward_default_kwargs ) __magic_name__ = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ ) __magic_name__ = self.dummy_sample __magic_name__ = 0.1 * sample __magic_name__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __magic_name__ = self.get_scheduler_config(**UpperCamelCase__ ) __magic_name__ = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals __magic_name__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) __magic_name__ = scheduler_class.from_pretrained(UpperCamelCase__ ) new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals __magic_name__ = dummy_past_residuals[: new_scheduler.config.solver_order] __magic_name__ , __magic_name__ = sample, sample for t in range(UpperCamelCase__ , time_step + scheduler.config.solver_order + 1 ): __magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample __magic_name__ = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" pass def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict=0 , **UpperCamelCase__ : Any ) -> Any: """simple docstring""" __magic_name__ = dict(self.forward_default_kwargs ) __magic_name__ = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ ) __magic_name__ = self.dummy_sample __magic_name__ = 0.1 * sample __magic_name__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __magic_name__ = self.get_scheduler_config() __magic_name__ = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) __magic_name__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) __magic_name__ = scheduler_class.from_pretrained(UpperCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) __magic_name__ = dummy_past_residuals[: new_scheduler.config.solver_order] __magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample __magic_name__ = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _lowercase ( self : List[str] , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : List[str] ) -> Any: """simple docstring""" if scheduler is None: __magic_name__ = self.scheduler_classes[0] __magic_name__ = self.get_scheduler_config(**UpperCamelCase__ ) __magic_name__ = scheduler_class(**UpperCamelCase__ ) __magic_name__ = self.scheduler_classes[0] __magic_name__ = self.get_scheduler_config(**UpperCamelCase__ ) __magic_name__ = scheduler_class(**UpperCamelCase__ ) __magic_name__ = 10 __magic_name__ = self.dummy_model() __magic_name__ = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): __magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample return sample def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) __magic_name__ = 50 __magic_name__ = self.dummy_model() __magic_name__ = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase__ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): __magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.2574 ) < 1E-3 def _lowercase ( self : str ) -> str: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) __magic_name__ = self.full_loop(scheduler=UpperCamelCase__ ) __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 __magic_name__ = DEISMultistepScheduler.from_config(scheduler.config ) __magic_name__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) __magic_name__ = UniPCMultistepScheduler.from_config(scheduler.config ) __magic_name__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __magic_name__ = self.full_loop(scheduler=UpperCamelCase__ ) __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 def _lowercase ( self : Optional[int] ) -> List[str]: """simple docstring""" self.check_over_configs(thresholding=UpperCamelCase__ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=UpperCamelCase__ , prediction_type=UpperCamelCase__ , sample_max_value=UpperCamelCase__ , algorithm_type="""dpmsolver++""" , solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , ) def _lowercase ( self : Dict ) -> Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> Any: """simple docstring""" for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , prediction_type=UpperCamelCase__ , algorithm_type=UpperCamelCase__ , ) __magic_name__ = self.full_loop( solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , prediction_type=UpperCamelCase__ , algorithm_type=UpperCamelCase__ , ) assert not torch.isnan(UpperCamelCase__ ).any(), "Samples have nan numbers" def _lowercase ( self : List[Any] ) -> str: """simple docstring""" self.check_over_configs(lower_order_final=UpperCamelCase__ ) self.check_over_configs(lower_order_final=UpperCamelCase__ ) def _lowercase ( self : str ) -> Union[str, Any]: """simple docstring""" self.check_over_configs(lambda_min_clipped=-float("""inf""" ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def _lowercase ( self : List[str] ) -> List[str]: """simple docstring""" self.check_over_configs(variance_type=UpperCamelCase__ ) self.check_over_configs(variance_type="""learned_range""" ) def _lowercase ( self : List[str] ) -> Optional[int]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=UpperCamelCase__ , time_step=0 ) def _lowercase ( self : str ) -> Any: """simple docstring""" __magic_name__ = self.full_loop() __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.full_loop(use_karras_sigmas=UpperCamelCase__ ) __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.2248 ) < 1E-3 def _lowercase ( self : Optional[int] ) -> List[str]: """simple docstring""" __magic_name__ = self.full_loop(prediction_type="""v_prediction""" ) __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.1453 ) < 1E-3 def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.full_loop(prediction_type="""v_prediction""" , use_karras_sigmas=UpperCamelCase__ ) __magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 0.0649 ) < 1E-3 def _lowercase ( self : List[Any] ) -> Any: """simple docstring""" __magic_name__ = self.scheduler_classes[0] __magic_name__ = self.get_scheduler_config(thresholding=UpperCamelCase__ , dynamic_thresholding_ratio=0 ) __magic_name__ = scheduler_class(**UpperCamelCase__ ) __magic_name__ = 10 __magic_name__ = self.dummy_model() __magic_name__ = self.dummy_sample_deter.half() scheduler.set_timesteps(UpperCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): __magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample assert sample.dtype == torch.floataa
76
import math import random def a__ ( A_, A_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __lowerCAmelCase : Union[str, Any] = 0.02 def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = float(2 * (random.randint(1, 100 )) - 1 ) for _ in range(A_ ): # Forward propagation __magic_name__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __magic_name__ = (expected / 100) - layer_a # Error delta __magic_name__ = layer_1_error * sigmoid_function(A_, A_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : List[Any] = int(input('Expected value: ')) __lowerCAmelCase : Tuple = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
76
1
# coding=utf-8 # Copyright 2023 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 platform import sys __lowerCAmelCase : List[str] = '3' print('Python version:', sys.version) print('OS platform:', platform.platform()) print('OS architecture:', platform.machine()) 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()) except ImportError: print('Torch version:', None) try: import transformers print('transformers version:', transformers.__version__) except ImportError: print('transformers version:', None)
76
import os import sys __lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __lowerCAmelCase : Union[str, Any] = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoConfig.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoTokenizer.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModel.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModel.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def a__ ( *A_, **A_ ): '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
76
1
import numpy as np def a__ ( 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_ ) __magic_name__ = 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. __magic_name__ = False __magic_name__ = 0 __magic_name__ = 0 __magic_name__ = 1e12 while not convergence: # Multiple matrix by the vector. __magic_name__ = np.dot(A_, A_ ) # Normalize the resulting output vector. __magic_name__ = w / np.linalg.norm(A_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __magic_name__ = vector.conj().T if is_complex else vector.T __magic_name__ = np.dot(A_, np.dot(A_, A_ ) ) # Check convergence. __magic_name__ = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __magic_name__ = True __magic_name__ = lambda_ if is_complex: __magic_name__ = np.real(lambda_ ) return lambda_, vector def a__ ( ): '''simple docstring''' __magic_name__ = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __magic_name__ = np.array([41, 4, 20] ) __magic_name__ = real_input_matrix.astype(np.complexaaa ) __magic_name__ = np.triu(1j * complex_input_matrix, 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __magic_name__ = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __magic_name__ = real_input_matrix __magic_name__ = real_vector elif problem_type == "complex": __magic_name__ = complex_input_matrix __magic_name__ = complex_vector # Our implementation. __magic_name__ , __magic_name__ = power_iteration(A_, A_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __magic_name__ , __magic_name__ = np.linalg.eigh(A_ ) # Last eigenvalue is the maximum one. __magic_name__ = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __magic_name__ = 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()
76
from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str: """simple docstring""" if tokenize_kwargs is None: __magic_name__ = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) __magic_name__ = truncation __magic_name__ = tokenize_kwargs __magic_name__ = {} if return_tensors is not None: __magic_name__ = return_tensors return preprocess_params, {}, postprocess_params def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]: """simple docstring""" __magic_name__ = self.framework __magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) return model_inputs def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str: """simple docstring""" __magic_name__ = self.model(**UpperCamelCase__ ) return model_outputs def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]: """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
76
1
def a__ ( A_, A_ ): '''simple docstring''' if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
76
import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __lowerCAmelCase : str = { 'gwf-440k': { 'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-small-190k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt', 'sample_rate': 48000, 'sample_size': 65536, }, 'jmann-large-580k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt', 'sample_rate': 48000, 'sample_size': 131072, }, 'maestro-uncond-150k': { 'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'unlocked-uncond-250k': { 'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, 'honk-140k': { 'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt', 'sample_rate': 16000, 'sample_size': 65536, }, } def a__ ( A_, A_ ): '''simple docstring''' return torch.atana(A_, A_ ) / math.pi * 2 def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.sin(t * math.pi / 2 ) ** 2 __magic_name__ = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(A_, A_ ) class UpperCAmelCase_ ( _A ): '''simple docstring''' pass class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]: """simple docstring""" super().__init__() __magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 ) __magic_name__ = deepcopy(self.diffusion ) __magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ ) def a__ ( A_ ): '''simple docstring''' __magic_name__ = MODELS_MAP[model_name]["""url"""] os.system(f'''wget {url} ./''' ) return f'''./{model_name}.ckpt''' __lowerCAmelCase : Optional[int] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', } __lowerCAmelCase : Optional[Any] = { '8': 'resnets.0', '9': 'attentions.0', '10': 'resnets.1', '11': 'attentions.1', '12': 'resnets.2', '13': 'attentions.2', } __lowerCAmelCase : Union[str, Any] = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', '8': 'resnets.3', '9': 'attentions.3', '10': 'resnets.4', '11': 'attentions.4', '12': 'resnets.5', '13': 'attentions.5', } __lowerCAmelCase : int = { '0': 'resnets.0', '1': 'resnets.1', '2': 'resnets.2', '4': 'resnets.0', '5': 'resnets.1', '6': 'resnets.2', } __lowerCAmelCase : List[str] = { 'skip': 'conv_skip', 'main.0': 'conv_1', 'main.1': 'group_norm_1', 'main.3': 'conv_2', 'main.4': 'group_norm_2', } __lowerCAmelCase : int = { 'norm': 'group_norm', 'qkv_proj': ['query', 'key', 'value'], 'out_proj': ['proj_attn'], } def a__ ( A_ ): '''simple docstring''' if name.startswith("""skip""" ): return name.replace("""skip""", RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f'''ResConvBlock error with {name}''' ) return name.replace(name[:6], RES_CONV_MAP[name[:6]] ) def a__ ( A_ ): '''simple docstring''' for key, value in ATTN_MAP.items(): if name.startswith(A_ ) and not isinstance(A_, A_ ): return name.replace(A_, A_ ) elif name.startswith(A_ ): return [name.replace(A_, A_ ) for v in value] raise ValueError(f'''Attn error with {name}''' ) def a__ ( A_, A_=13 ): '''simple docstring''' __magic_name__ = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""", """time_proj""" ) __magic_name__ = 0 if string.startswith("""net.3.""" ): depth += 1 __magic_name__ = string[6:] elif string.startswith("""net.""" ): __magic_name__ = string[4:] while string.startswith("""main.7.""" ): depth += 1 __magic_name__ = string[7:] if string.startswith("""main.""" ): __magic_name__ = string[5:] # mid block if string[:2].isdigit(): __magic_name__ = string[:2] __magic_name__ = string[2:] else: __magic_name__ = string[0] __magic_name__ = string[1:] if depth == max_depth: __magic_name__ = MID_NUM_TO_LAYER[layer_num] __magic_name__ = """mid_block""" elif depth > 0 and int(A_ ) < 7: __magic_name__ = DOWN_NUM_TO_LAYER[layer_num] __magic_name__ = f'''down_blocks.{depth}''' elif depth > 0 and int(A_ ) > 7: __magic_name__ = UP_NUM_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - depth - 1}''' elif depth == 0: __magic_name__ = DEPTH_0_TO_LAYER[layer_num] __magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' ) __magic_name__ = string_left[1:] if "resnets" in new_layer: __magic_name__ = convert_resconv_naming(A_ ) elif "attentions" in new_layer: __magic_name__ = convert_attn_naming(A_ ) __magic_name__ = new_string_left if not isinstance(A_, A_ ): __magic_name__ = prefix + """.""" + new_layer + """.""" + string_left else: __magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def a__ ( A_ ): '''simple docstring''' __magic_name__ = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue __magic_name__ = rename(A_ ) # check if we need to transform from Conv => Linear for attention if isinstance(A_, A_ ): __magic_name__ = transform_conv_attns(A_, A_, A_ ) else: __magic_name__ = v return new_state_dict def a__ ( A_, A_, A_ ): '''simple docstring''' if len(A_ ) == 1: if len(v.shape ) == 3: # weight __magic_name__ = v[:, :, 0] else: # bias __magic_name__ = v else: # qkv matrices __magic_name__ = v.shape[0] __magic_name__ = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __magic_name__ = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def a__ ( A_ ): '''simple docstring''' __magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}''' __magic_name__ = download(A_ ) __magic_name__ = MODELS_MAP[model_name]["""sample_rate"""] __magic_name__ = MODELS_MAP[model_name]["""sample_size"""] __magic_name__ = Object() __magic_name__ = sample_size __magic_name__ = sample_rate __magic_name__ = 0 __magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ ) __magic_name__ = diffusers_model.state_dict() __magic_name__ = DiffusionUncond(A_ ) orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] ) __magic_name__ = orig_model.diffusion_ema.eval() __magic_name__ = orig_model.state_dict() __magic_name__ = rename_orig_weights(A_ ) __magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}''' assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}''' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}''' if key == "time_proj.weight": __magic_name__ = value.squeeze() __magic_name__ = value diffusers_model.load_state_dict(A_ ) __magic_name__ = 100 __magic_name__ = 33 __magic_name__ = IPNDMScheduler(num_train_timesteps=A_ ) __magic_name__ = torch.manual_seed(A_ ) __magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ ) __magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1] __magic_name__ = get_crash_schedule(A_ ) __magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ ) __magic_name__ = torch.manual_seed(33 ) __magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios __magic_name__ = sampling.iplms_sample(A_, A_, A_, {} ) __magic_name__ = generated.clamp(-1, 1 ) __magic_name__ = (generated - audio).abs().sum() __magic_name__ = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""", A_ ) print("""Diff max""", A_ ) assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/''' print(f'''Conversion for {model_name} successful!''' ) if __name__ == "__main__": __lowerCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') 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=None, type=str, required=True, help='Path to the output model.') __lowerCAmelCase : Union[str, Any] = parser.parse_args() main(args)
76
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Any = logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """open-llama""" def __init__( self : Dict , UpperCamelCase__ : Tuple=10_0000 , UpperCamelCase__ : Union[str, Any]=4096 , UpperCamelCase__ : Any=1_1008 , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : List[str]=32 , UpperCamelCase__ : Optional[int]="silu" , UpperCamelCase__ : str=2048 , UpperCamelCase__ : Optional[int]=0.02 , UpperCamelCase__ : List[str]=1E-6 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : str=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[str]=2 , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Any=True , UpperCamelCase__ : Tuple=None , **UpperCamelCase__ : int , ) -> List[str]: """simple docstring""" __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = use_cache __magic_name__ = kwargs.pop( """use_memorry_efficient_attention""" , UpperCamelCase__ ) __magic_name__ = hidden_dropout_prob __magic_name__ = attention_dropout_prob __magic_name__ = use_stable_embedding __magic_name__ = shared_input_output_embedding __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , tie_word_embeddings=UpperCamelCase__ , **UpperCamelCase__ , ) def _lowercase ( self : Optional[Any] ) -> Dict: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , UpperCamelCase__ ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ F'''got {self.rope_scaling}''' ) __magic_name__ = self.rope_scaling.get("""type""" , UpperCamelCase__ ) __magic_name__ = self.rope_scaling.get("""factor""" , UpperCamelCase__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """lilt""" def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = classifier_dropout __magic_name__ = channel_shrink_ratio __magic_name__ = max_ad_position_embeddings
76
1
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : str = logging.get_logger(__name__) def a__ ( A_ ): '''simple docstring''' __magic_name__ = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __magic_name__ = 128 elif "12-12" in model_name: __magic_name__ = 12 __magic_name__ = 12 elif "14-14" in model_name: __magic_name__ = 14 __magic_name__ = 14 elif "16-16" in model_name: __magic_name__ = 16 __magic_name__ = 16 else: raise ValueError("""Model not supported""" ) __magic_name__ = """huggingface/label-files""" if "speech-commands" in model_name: __magic_name__ = 35 __magic_name__ = """speech-commands-v2-id2label.json""" else: __magic_name__ = 527 __magic_name__ = """audioset-id2label.json""" __magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) ) __magic_name__ = {int(A_ ): v for k, v in idalabel.items()} __magic_name__ = idalabel __magic_name__ = {v: k for k, v in idalabel.items()} return config def a__ ( A_ ): '''simple docstring''' if "module.v" in name: __magic_name__ = name.replace("""module.v""", """audio_spectrogram_transformer""" ) if "cls_token" in name: __magic_name__ = name.replace("""cls_token""", """embeddings.cls_token""" ) if "dist_token" in name: __magic_name__ = name.replace("""dist_token""", """embeddings.distillation_token""" ) if "pos_embed" in name: __magic_name__ = name.replace("""pos_embed""", """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __magic_name__ = name.replace("""patch_embed.proj""", """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __magic_name__ = name.replace("""blocks""", """encoder.layer""" ) if "attn.proj" in name: __magic_name__ = name.replace("""attn.proj""", """attention.output.dense""" ) if "attn" in name: __magic_name__ = name.replace("""attn""", """attention.self""" ) if "norm1" in name: __magic_name__ = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: __magic_name__ = name.replace("""norm2""", """layernorm_after""" ) if "mlp.fc1" in name: __magic_name__ = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: __magic_name__ = name.replace("""mlp.fc2""", """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __magic_name__ = name.replace("""audio_spectrogram_transformer.norm""", """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __magic_name__ = name.replace("""module.mlp_head.0""", """classifier.layernorm""" ) if "module.mlp_head.1" in name: __magic_name__ = name.replace("""module.mlp_head.1""", """classifier.dense""" ) return name def a__ ( A_, A_ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __magic_name__ = orig_state_dict.pop(A_ ) if "qkv" in key: __magic_name__ = key.split(""".""" ) __magic_name__ = int(key_split[3] ) __magic_name__ = config.hidden_size if "weight" in key: __magic_name__ = val[:dim, :] __magic_name__ = val[dim : dim * 2, :] __magic_name__ = val[-dim:, :] else: __magic_name__ = val[:dim] __magic_name__ = val[dim : dim * 2] __magic_name__ = val[-dim:] else: __magic_name__ = val return orig_state_dict def a__ ( A_ ): '''simple docstring''' __magic_name__ = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(A_, A_ ) @torch.no_grad() def a__ ( A_, A_, A_=False ): '''simple docstring''' __magic_name__ = get_audio_spectrogram_transformer_config(A_ ) __magic_name__ = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __magic_name__ = model_name_to_url[model_name] __magic_name__ = torch.hub.load_state_dict_from_url(A_, map_location="""cpu""" ) # remove some keys remove_keys(A_ ) # rename some keys __magic_name__ = convert_state_dict(A_, A_ ) # load 🤗 model __magic_name__ = ASTForAudioClassification(A_ ) model.eval() model.load_state_dict(A_ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __magic_name__ = -4.2677393 if """speech-commands""" not in model_name else -6.845978 __magic_name__ = 4.5689974 if """speech-commands""" not in model_name else 5.5654526 __magic_name__ = 1024 if """speech-commands""" not in model_name else 128 __magic_name__ = ASTFeatureExtractor(mean=A_, std=A_, max_length=A_ ) if "speech-commands" in model_name: __magic_name__ = load_dataset("""speech_commands""", """v0.02""", split="""validation""" ) __magic_name__ = dataset[0]["""audio"""]["""array"""] else: __magic_name__ = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""", filename="""sample_audio.flac""", repo_type="""dataset""", ) __magic_name__ , __magic_name__ = torchaudio.load(A_ ) __magic_name__ = waveform.squeeze().numpy() __magic_name__ = feature_extractor(A_, sampling_rate=16000, return_tensors="""pt""" ) # forward pass __magic_name__ = model(**A_ ) __magic_name__ = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __magic_name__ = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __magic_name__ = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __magic_name__ = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __magic_name__ = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __magic_name__ = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __magic_name__ = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __magic_name__ = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __magic_name__ = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3], A_, atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(A_ ).mkdir(exist_ok=A_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(A_ ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f'''MIT/{model_name}''' ) feature_extractor.push_to_hub(f'''MIT/{model_name}''' ) if __name__ == "__main__": __lowerCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : Any = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class UpperCAmelCase_ : '''simple docstring''' a__ = None def _lowercase ( self : Optional[int] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__ = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" ) feat_extract_first.to_json_file(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : str ) -> str: """simple docstring""" __magic_name__ = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) __magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _lowercase ( self : Optional[int] ) -> Tuple: """simple docstring""" __magic_name__ = self.feature_extraction_class() self.assertIsNotNone(UpperCamelCase__ )
76
1
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures __lowerCAmelCase : List[Any] = logging.get_logger(__name__) @dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys() )} ) a__ = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a__ = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ = field( default=_A , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.task_name.lower() class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """train""" a__ = """dev""" a__ = """test""" class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = 42 a__ = 42 a__ = 42 def __init__( self : Tuple , UpperCamelCase__ : GlueDataTrainingArguments , UpperCamelCase__ : PreTrainedTokenizerBase , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Union[str, Split] = Split.train , UpperCamelCase__ : Optional[str] = None , ) -> Any: """simple docstring""" warnings.warn( """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , UpperCamelCase__ , ) __magic_name__ = args __magic_name__ = glue_processors[args.task_name]() __magic_name__ = glue_output_modes[args.task_name] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): try: __magic_name__ = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) # Load data features from cache or dataset file __magic_name__ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' , ) __magic_name__ = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) __magic_name__ , __magic_name__ = label_list[2], label_list[1] __magic_name__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __magic_name__ = cached_features_file + """.lock""" with FileLock(UpperCamelCase__ ): if os.path.exists(UpperCamelCase__ ) and not args.overwrite_cache: __magic_name__ = time.time() __magic_name__ = torch.load(UpperCamelCase__ ) logger.info( F'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start ) else: logger.info(F'''Creating features from dataset file at {args.data_dir}''' ) if mode == Split.dev: __magic_name__ = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: __magic_name__ = self.processor.get_test_examples(args.data_dir ) else: __magic_name__ = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: __magic_name__ = examples[:limit_length] __magic_name__ = glue_convert_examples_to_features( UpperCamelCase__ , UpperCamelCase__ , max_length=args.max_seq_length , label_list=UpperCamelCase__ , output_mode=self.output_mode , ) __magic_name__ = time.time() torch.save(self.features , UpperCamelCase__ ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self : Optional[int] ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self : List[Any] , UpperCamelCase__ : List[str] ) -> InputFeatures: """simple docstring""" return self.features[i] def _lowercase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return self.label_list
76
from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_A ): '''simple docstring''' a__ = ["""note_seq"""] def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""note_seq"""] ) @classmethod def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" requires_backends(cls , ["""note_seq"""] ) @classmethod def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int: """simple docstring""" requires_backends(cls , ["""note_seq"""] )
76
1